O'Reilly logo

Professional C# 2008 by Karli Watson, Morgan Skinner, Jay Glynn, Bill Evjen, Christian Nagel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5

Arrays

If you need to work with multiple objects of the same type, you can use collections and arrays. C# has a special notation to declare and use arrays. Behind the scenes, the Array class comes into play, which offers several methods to sort and filter the elements inside the array.

Using an enumerator, you can iterate through all the elements of an array.

This chapter discusses the following:

  • Simple arrays
  • Multidimensional arrays
  • Jagged arrays
  • The Array class
  • Interfaces for arrays
  • Enumerations

Simple Arrays

If you need to use multiple objects of the same type, you can use an array. An array is a data structure that contains a number of elements of the same type.

Array Declaration

An array is declared by defining the type of the elements inside the array followed by empty brackets and a variable name; for example, an array containing integer elements is declared like this:

int[] myArray;

Array Initialization

After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated. You do this by initializing the variable of the array using the new operator with the type and the number of elements inside the array. Here you specify the size of the array:

myArray = new int[4];

Value and reference types are covered in Chapter 3, “Objects and Types.”

With this declaration and initialization, the variable myArray references four integer values that are allocated on the managed ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required