Name

Array

Synopsis

Unlike other environments (such as C++), .NET has arrays of first-class type, in that all array types are derivatives of the base type Array. All methods are available on any array type, regardless of its declaration. In fact, the CLR is required to synthesize a pseudotype that matches the declaration. Thus, when you declare a variable of type string[], the CLR creates an anonymous type, deriving from Array specifically for storing Strings in a one-dimensional array.

The Array class has a number of useful array-related methods, such as checking for bounds violations (attempting to access an element of the array that isn’t in the array’s declared size) and retrieval of array length. In addition, because Array also implements the ICloneable, System.Collections.IList, System.Collections.ICollection and System.Collections.IEnumerable interfaces, arrays can be used anywhere these interface types are expected.

Arrays are reference types. This means that the statement ArrayB = ArrayA results in two objects that reference the same array. Use ArrayB = ArrayA.Clone() to create a duplicate copy of an array. This will be a shallow copy with identical references to subobjects. To create a deep copy in which each array has its own copy of subobjects, you must loop through the array and assign values manually.

The Array class also contains useful static methods. These include IndexOf(), which returns the offset of the first matching occurrence of an object in an array. For ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.