15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

array Class ❘ 135<br />

The CreateInstance() method has many overloads to create multidimensional arrays <strong>and</strong> also to create<br />

arrays that are not 0-based. The following example creates a two-dimensional array with 2 3 elements.<br />

The first dimension is 1-based; the second dimension is 10-based.<br />

int[] lengths = { 2, 3 };<br />

int[] lowerBounds = { 1, 10 };<br />

Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds);<br />

Setting the elements of the array, the SetValue() method accepts indices for every dimension:<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Alain",<br />

LastName = "Prost"<br />

}, 1, 10);<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Emerson",<br />

LastName = "Fittipaldi"<br />

}, 1, 11);<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Ayrton",<br />

LastName = "Senna"<br />

}, 1, 12);<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Ralf",<br />

LastName = "Schumacher"<br />

}, 2, 10);<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Fern<strong>and</strong>o",<br />

LastName = "Alonso"<br />

}, 2, 11);<br />

racers.SetValue(new Person<br />

{<br />

FirstName = "Jenson",<br />

LastName = "Button"<br />

}, 2, 12);<br />

code snippet Sample1/Program.cs<br />

Although the array is not 0-based, you can assign it to a variable with the normal <strong>C#</strong> notation. You just<br />

have to pay attention not to cross the boundaries.<br />

Person[,] racers2 = (Person[,])racers;<br />

Person first = racers2[1, 10];<br />

Person last = racers2[2, 12];<br />

Copying arrays<br />

Because arrays are reference types, assigning an array variable to another<br />

one just gives you two variables referencing the same array. For copying<br />

arrays, the array implements the interface ICloneable. The Clone()<br />

method that is defined with this interface creates a shallow copy of the array.<br />

If the elements of the array are value types, as in the following code<br />

segment, all values are copied, as you can see in Figure 6-5.<br />

int[] intArray1 = {1, 2};<br />

int[] intArray2 = (int[])intArray1.Clone();<br />

intArray1 1<br />

2<br />

intArray2 1<br />

2<br />

figure 6-5<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!