Type System.Array

extends System.Object

extends System.ICloneable

extends System.Collections.IList

extends System.Collections.ICollection

extends System.Collections.IEnumerable

Variables:

public System.Boolean IsFixedSize

public System.Boolean IsReadOnly

public System.Boolean IsSynchronized

public System.Int32 Length

public System.Int64 LongLength

public System.Int32 Rank

public System.Object SyncRoot

public System.Int32 System.Collections.ICollection.Count

public virtual System.Object System.Collections.IList.Item

Constructors:

private System.Array()

Constructs a new instance of the System.Array class.

Functions:

public static System.Int32 BinarySearch(System.Array array, System.Int32 index, System.Int32 length, System.Object value, System.Collections.IComparer comparer)

Searches the specified section of the specified one-dimensional System.Array for the specified value, using the specified System.Collections.IComparer implementation.

Parameter array: A System.Array to search.

Parameter index: A System.Int32 that contains the index at which searching starts.

Parameter length: A System.Int32 that contains the number of elements to search, beginning with index .

Parameter value: A System.Object for which to search, or a null reference. A null reference will be considered to compare less than any non-null object, or equal to another null reference.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Returns: A System.Int32 with one of the following values based on the result of the search operation. If value is not found, the caller can take the bitwise complement of the return value to determine the index of array where value would be found in the range of index to index + length - 1 if array is already sorted.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: index and length do not specify a valid range in array (i.e. index + length > array.GetLowerBound(0) + array.Length). -or- comparer is null, and both value and at least one element of array do not implement the System.IComparable interface. -or- comparer is null, and value is not of the same type as the elements of array. -or- array.UpperBound == System.Int32.MaxValue.

value is compared to each element of array using comparer until an element with a value greater than or equal to value is found. If comparer is null, the System.IComparable interface of the element being compared - or of value if the element being compared does not implement the interface -- is used. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.

Example:

This example demonstrates the System.Array.BinarySearch(System.Array,System.Object) method.

using System;
class BinarySearchExample {
  public static void Main() {    
    int[] intAry = { 0, 2, 4, 6, 8 };
    Console.WriteLine( "The indices and elements of the array are: ");
    for ( int i = 0; i < intAry.Length; i++ )
      Console.Write("[{0}]: {1, -5}", i, intAry[i]);
    Console.WriteLine();
    SearchFor( intAry, 3 );
    SearchFor( intAry, 6 );
    SearchFor( intAry, 9 );
  }
  public static void SearchFor( Array ar, Object value ) {
    int i = Array.BinarySearch( ar, 0, ar.Length, value, null );
    Console.WriteLine();
    if ( i > 0 ) {
      Console.Write( "The object searched for, {0}, was found ", value );
      Console.WriteLine( "at index {1}.", value, i );
    }
    else if ( ~i == ar.Length ) {
      Console.Write( "The object searched for, {0}, was ", value );
      Console.Write( "not found,\nand no object in the array had " );
      Console.WriteLine( "greater value. " );
    }
    else {
      Console.Write( "The object searched for, {0}, was ", value );
      Console.Write( "not found.\nThe next larger object is at " );
      Console.WriteLine( "index {0}.", ~i );
    }
  }
}
   

The output is

The indices and elements of the array are:

[0]:0 [1]:2 [2]:4 [3]:6 [4]:8

The object searched for, 3, was not found.

The next larger object is at index 2.

The object searched for, 6, was found at index 3.

The object searched for, 9, was not found,

and no object in the array had greater value.

public static System.Int32 BinarySearch(System.Array array, System.Object value, System.Collections.IComparer comparer)

Searches the specified one-dimensional System.Array for the specified value, using the specified System.Collections.IComparer implementation.

Parameter array: A System.Array to search.

Parameter value: A System.Object for which to search, or a null reference. A null reference will be considered to compare less than any non-null object, or equal to another null reference.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Returns: A System.Int32 with one of the following values based on the result of the search operation. If value is not found, the caller can take the bitwise complement of the return value to determine the index where value would be found in array if it is already sorted.

Throws: System.ArgumentException: comparer is null, and both value and at least one element of array do not implement the System.IComparable interface. -or- comparer is null, and value is not assignment-compatible with at least one element of array. -or- array.UpperBound == System.Int32.MaxValue.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.BinarySearch(System.Array,System.Object) is equivalent to System.Array.BinarySearch(System.Array,System.Object)(array, array.GetLowerBound(0), array.Length, value, comparer). value is compared to each element of array using comparer until an element with a value greater than or equal to value is found. If comparer is null, the System.IComparable interface of the element being compared - or of value if the element being compared does not implement the interface - is used. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.

public static System.Int32 BinarySearch(System.Array array, System.Int32 index, System.Int32 length, System.Object value)

Searches the specified section of the specified one-dimensional System.Array for the specified value.

Parameter array: A System.Array to search.

Parameter index: A System.Int32 that contains the index at which searching starts.

Parameter length: A System.Int32 that contains the number of elements to search, beginning with index .

Parameter value: A System.Object for which to search, or a null reference. A null reference will be considered to compare less than any non-null object, or equal to another null reference.

Returns: A System.Int32 with one of the following values based on the result of the search operation. If value is not found, the caller can take the bitwise complement of the return value to determine the index of the array where value would be found in the range of index to index + length - 1 if array is already sorted.

Throws: System.ArgumentNullException: array is null .

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: index and length do not specify a valid range in array (i.e. index + length > array.GetLowerBound(0) + array.Length). -or- Either value or at least one element of array does not implement the System.IComparable interface. -or- value is not assignment-compatible with at least one element of array. -or- array.UpperBound == System.Int32.MaxValue.

This version of System.Array.BinarySearch(System.Array,System.Object) is equivalent to System.Array.BinarySearch(System.Array,System.Object)(array, array.GetLowerBound(0), array.Length, value, null). value is compared to each element of array using the System.IComparable interface of the element being compared - or of value if the element being compared does not implement the interface - until an element with a value greater than or equal to value is found. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.

public static System.Int32 BinarySearch(System.Array array, System.Object value)

Searches the specified one-dimensional System.Array for the specified object.

Parameter array: A System.Array to search for an object.

Parameter value: A System.Object for which to search, or a null reference. A null reference will be considered to compare less than any non-null object, or equal to another null reference.

Returns: A System.Int32 with one of the following values based on the result of the search operation. If value is not found, the caller can take the bitwise complement of the return value to determine the index where value would be found in array if it is sorted already.

Throws: System.ArgumentException: Both value and at least one element of array do not implement the System.IComparable interface. -or- value is not assignment-compatible with at least one element of array. -or- array.UpperBound == System.Int32.MaxValue.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.BinarySearch(System.Array,System.Object) is equivalent to System.Array.BinarySearch(System.Array,System.Object)(array, array.GetLowerBound(0), array.Length, value, null). value is compared to each element of array using the System.IComparable interface of the element being compared - or of value if the element being compared does not implement the interface - until an element with a value greater than or equal to value is found. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.

public static System.Void Clear(System.Array array, System.Int32 index, System.Int32 length)

Sets the specified range of elements in the specified System.Array to zero, false, or to a null reference, depending on the element type.

Parameter array: The System.Array to clear.

Parameter index: A System.Int32 that contains the index at which clearing starts.

Parameter length: A System.Int32 that contains the number of elements to clear, beginning with index.

Throws: System.ArgumentNullException: array is null.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). length < 0. index and length do not specify a valid range in array (i.e. index + length > array.GetLowerBound(0) + array.Length ).

Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false.

public virtual System.Object Clone()

Returns a System.Object that is a copy of the current instance.

Returns: A System.Object that is a copy of the current instance.

This method is implemented to support the System.ICloneable interface. Each of the elements of the current instance is copied to the clone. If the elements are reference types, the references are copied. If the elements are value-types, the values are copied. The clone is of the same type as the current instance. As described above. Override this method to return a clone of an array. Use this method to obtain the clone of an array.

Example:

This example demonstrates the System.Array.Clone method.

using System;
public class ArrayCloneExample {
  public static void Main() {
    int[] intAryOrig = { 3, 4, 5 };
    //must explicitly convert clones object into an array
    int[] intAryClone = (int[]) intAryOrig.Clone();
    Console.Write( "The elements of the first  array are: " );
    foreach( int i in intAryOrig )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    Console.Write( "The elements of the cloned array are: " );
    foreach( int i in intAryClone )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    //Clear the values of the original array.
    Array.Clear( intAryOrig, 0, 3 );
    Console.WriteLine( "After clearing the first array," );
    Console.Write( "The elements of the first  array are: " );
    foreach( int i in intAryOrig )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    Console.Write( "The elements of the cloned array are: " );
    foreach( int i in intAryClone )
      Console.Write( "{0,3}", i );
  }
}
   

The output is

The elements of the first array are: 3 4 5

The elements of the cloned array are: 3 4 5

After clearing the first array,

The elements of the first array are: 0 0 0

The elements of the cloned array are: 3 4 5

public static System.Void Copy(System.Array sourceArray, System.Array destinationArray, System.Int32 length)

Copies the specified number of elements from the specified source array to the specified destination array.

Parameter sourceArray: A System.Array that contains the data to copy.

Parameter destinationArray: A System.Array that receives the data.

Parameter length: A System.Int32 designating the number of elements to copy, starting with the first element and proceeding in order.

Throws: System.ArgumentNullException: sourceArray or destinationArray is null.

Throws: System.RankException: sourceArray and destinationArray have different ranks.

Throws: System.ArrayTypeMismatchException: The elements in both arrays are built-in types, and converting from the type of the elements of sourceArray into the type of the elements in destinationArray requires a narrowing conversion. -or- Both arrays are built-in types, and one array is a value-type array and the other an array of interface type not implemented by that value-type. -or- Both arrays are user-defined value types and are not of the same type.

Throws: System.InvalidCastException: At least one of the elements in sourceArray is not assignment-compatible with the type of destinationArray.

Throws: System.ArgumentOutOfRangeException: length < 0.

Throws: System.ArgumentException: length > sourceArray.Length. -or- length > destinationArray.Length.

This version of System.Array.Copy(System.Array,System.Array,System.Int32) is equivalent to System.Array.Copy(System.Array,System.Array,System.Int32) (sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length). If sourceArray and destinationArray are of different types, System.Array.Copy(System.Array,System.Array,System.Int32) performs widening conversions on the elements of sourceArray as necessary before storing the information in destinationArray. Value types will be boxed when being converted to a System.Object. If the necessary conversion is a narrowing conversion, a System.ArrayTypeMismatchException exception is thrown. For information regarding valid conversions performed by this method, see System.Convert. If an exception is thrown while copying, the state of destinationArray is undefined. If sourceArray and destinationArray are the same array, System.Array.Copy(System.Array,System.Array,System.Int32) copies the source elements safely to their destination, as if the copy were done through an intermediate array.

Example:

This example demonstrates the System.Array.Copy(System.Array,System.Array,System.Int32) method.

using System;
public class ArrayCopyExample {
   public static void Main() {
      int[] intAryOrig = new int[3];
      double[] dAryCopy = new double[3];
      for ( int i = 0; i < intAryOrig.Length; i++ )
         intAryOrig[i] = i+3;
      //copy the first 2 elements of the source into the destination
      Array.Copy( intAryOrig, dAryCopy, 2);
      Console.Write( "The elements of the first array are: " );
      for ( int i = 0; i < intAryOrig.Length; i++ ) 
         Console.Write( "{0,3}", intAryOrig[i] );
      Console.WriteLine();
      Console.Write( "The elements of the copied array are: " );
      for ( int i = 0; i < dAryCopy.Length; i++ ) 
         Console.Write( "{0,3}", dAryCopy[i] );
   }
}
   

The output is

The elements of the first array are: 3 4 5

The elements of the copied array are: 3 4 0

public static System.Void Copy(System.Array sourceArray, System.Int32 sourceIndex, System.Array destinationArray, System.Int32 destinationIndex, System.Int32 length)

Copies the specified number of elements from a source array starting at the specified source index to a destination array starting at the specified destination index.

Parameter sourceArray: The System.Array that contains the data to copy.

Parameter sourceIndex: A System.Int32 that contains the index in sourceArray from which copying begins.

Parameter destinationArray: The System.Array that receives the data.

Parameter destinationIndex: A System.Int32 that contains the index in destinationArray at which storing begins.

Parameter length: A System.Int32 that contains the number of elements to copy.

Throws: System.ArgumentNullException: sourceArray or destinationArray is null.

Throws: System.RankException: sourceArray and destinationArray have different ranks.

Throws: System.ArrayTypeMismatchException: The elements in both arrays are built-in types, and converting from the type of the elements of sourceArray into the type of the elements in destinationArray requires a narrowing conversion. -or- Both arrays are built-in types, and one array is a value-type array and the other an array of interface type not implemented by that value-type. -or- Both arrays are user-defined value types and are not of the same type.

Throws: System.InvalidCastException: At least one element in sourceArray is assignment-incompatible with the type of destinationArray.

Throws: System.ArgumentOutOfRangeException: sourceIndex < sourceArray.GetLowerBound(0). -or- destinationIndex < destinationArray.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: (sourceIndex + length ) > (sourceArray.GetLowerBound(0) + sourceArray.Length). (destinationIndex + length ) > ( destinationArray.GetLowerBound(0) + destinationArray.Length).

If sourceArray and destinationArray are of different types, System.Array.Copy(System.Array,System.Array,System.Int32) performs widening conversions on the elements of sourceArray as necessary before storing the information in destinationArray. Value types will be boxed when being converted to a System.Object. If the necessary conversion is a narrowing conversion, a System.ArrayTypeMismatchException exception is thrown. For information regarding valid conversions performed by this method, see System.Convert . If an exception is thrown while copying, the state of destinationArray is undefined. If sourceArray and destinationArray are the same array, System.Array.Copy(System.Array,System.Array,System.Int32) copies the source elements safely to their destination as if the copy were done through an intermediate array.

Example:

This example demonstrates the System.Array.Copy(System.Array,System.Array,System.Int32) method.

using System;
class ArrayCopyExample {
   public static void Main() {
      int[] intAry = { 0, 10, 20, 30, 40, 50 };
      Console.Write( "The elements of the array are: " );
      foreach ( int i in intAry )
         Console.Write( "{0,3}", i );
      Console.WriteLine();
      Array.Copy( intAry, 2, intAry, 0, 4 );
      Console.WriteLine( "After copying elements 2 through 5 into elements 0 through 4" );
      Console.Write( "The elements of the array are: " );
      foreach ( int i in intAry )
         Console.Write( "{0,3}", i );
      Console.WriteLine();     
   }
}
   

The output is

The elements of the array are: 0 10 20 30 40 50

After copying elements 2 through 5 into elements 0 through 4

The elements of the array are: 20 30 40 50 40 50

public virtual System.Void CopyTo(System.Array array, System.Int32 index)

Copies all the elements of the current instance to the specified one-dimensional array starting at the specified subscript in the destination array.

Parameter array: A one-dimensional System.Array that is the destination of the elements copied from the current instance.

Parameter index: A System.Int32 that contains the relative zero-based index in array at which copying begins.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: The current instance has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < 0.

Throws: System.ArgumentException: array has more than one dimension. -or- index is greater than or equal to array.Length. -or- The number of elements in the current instance is greater than the available space from index to the end of array.

Throws: System.ArrayTypeMismatchException: The type of the current instance cannot be cast automatically to the type of array.

index is an array index at which copying begins. This method is implemented to support the System.Collections.ICollection interface. If implementing System.Collections.ICollection is not explicitly required, use System.Array.Copy(System.Array,System.Array,System.Int32) to avoid an extra indirection. If the index of array is zero-based, this value is the same as the actual index at which copying begins. If the lower bound of array is not zero, the value of index is added to the lower bound of array to get the actual index at which copying begins. For example, if the lower bound of array is 2 and the value of index is 1, the copying actually starts at index 3. If this method throws an exception while copying, the state of array is undefined. As described above. As described above. Override this method to copy elements of the current instance to a specified array. Use this method to copy elements of the current instance to a specified array.

Example:

The following example shows how to copy the elements of one System.Array into another.

using System;

public class ArrayCopyToExample
{
   public static void Main()
   {
      Array aryOne = Array.CreateInstance(typeof(Object), 3);
      aryOne.SetValue("one", 0);
      aryOne.SetValue("two", 1);
      aryOne.SetValue("three", 2);

      Array aryTwo = Array.CreateInstance(typeof(Object), 5);
      for (int i=0; i < aryTwo.Length; i++)
         aryTwo.SetValue(i, i);

      Console.WriteLine("The contents of the first array are:");
      foreach (object o in aryOne)
         Console.Write("{0} ", o);
      Console.WriteLine();
      Console.WriteLine("The original contents of the second array are:");
      foreach (object o in aryTwo)
         Console.Write("{0} ", o);
      Console.WriteLine();
      
      aryOne.CopyTo(aryTwo, 1);

      Console.WriteLine("The new contents of the second array are:");
      foreach( object o in aryTwo)
         Console.Write("{0} ", o);
   }
}

The output is

The contents of the first array are:

one two three

The original contents of the second array are:

0 1 2 3 4

The new contents of the second array are:

0 one two three 4

public static System.Array CreateInstance(System.Type elementType, System.Int32[] lengths)

Creates a zero-based, multidimensional array of the specified System.Type and dimension lengths.

Parameter elementType: The System.Type of the elements contained in the new System.Array instance.

Parameter lengths: A one-dimensional array of System.Int32 objects that contains the size of each dimension of the new System.Array instance.

Returns: A new zero-based, multidimensional System.Array instance of the specified System.Type with the specified length for each dimension. The System.Array.Rank of the new instance is equal to lengths.Length.

Throws: System.ArgumentNullException: elementType orlengths is null.

Throws: System.ArgumentException: elementType is not a valid System.Type. -or- lengths.Length = 0.

Throws: System.ArgumentOutOfRangeException: A value in lengths is less than zero.

The number of elements in lengths is required to equal the number of dimensions in the new System.Array instance. Each element of lengths specifies the length of the corresponding dimension in the new instance. Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. Unlike most classes, System.Array provides the System.Array.CreateInstance(System.Type,System.Int32) method, instead of public constructors, to allow for late bound access.

Example:

The following example shows how to create and initialize a multidimensional System.Array.


using System;

public class CreateMultiDimArrayExample
{
   public static void Main()
   {
      int i, j, k;
      int[] indexAry = {2, 4, 5};
      Array ary = Array.CreateInstance( typeof(int), indexAry );
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++ )
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++ )
         {
            for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               ary.SetValue( (100*i + 10*j + k), i, j, k );
            }
         }
      }
      Console.WriteLine("The elements of the array are:");
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++)
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++)
         {
             for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               Console.Write("{0, 3} ", ary.GetValue(i, j, k));
            }
            Console.WriteLine();
         }
         Console.WriteLine();
      }
   }
}
   

The output is

The elements of the array are:
  0   1   2   3   4
 10  11  12  13  14
 20  21  22  23  24
 30  31  32  33  34

100 101 102 103 104
110 111 112 113 114
120 121 122 123 124
130 131 132 133 134 

public static System.Array CreateInstance(System.Type elementType, System.Int32 length1, System.Int32 length2, System.Int32 length3)

Creates a zero-based, three-dimensional array of the specified System.Type and dimension lengths.

Parameter elementType: The System.Type of the elements contained in the new System.Array instance.

Parameter length1: A System.Int32 that contains the number of elements contained in the first dimension of the new System.Array instance.

Parameter length2: A System.Int32 that contains the number of elements contained in the second dimension of the new System.Array instance.

Parameter length3: A System.Int32 that contains the number of elements contained in the third dimension of the new System.Array instance.

Returns: A new zero-based, three-dimensional System.Array instance of elementType objects with the size length1 for the first dimension, length2 for the second, and length3 for the third.

Throws: System.ArgumentNullException: elementType is null.

Throws: System.ArgumentException: elementType is not a valid System.Type.

Throws: System.ArgumentOutOfRangeException: length1 < 0. -or- length2 < 0. -or- length3 < 0.

Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. Unlike most classes, System.Array provides the System.Array.CreateInstance(System.Type,System.Int32) method, instead of public constructors, to allow for late bound access.

Example:

The following example shows how to create and initialize a three-dimensional System.Array.


using System;

public class Create3DArrayExample
{
   public static void Main()
   {
      int i, j, k;
      Array ary = Array.CreateInstance( typeof(int), 2, 4, 3 );
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++ )
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++ )
         {
            for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               ary.SetValue( (100*i + 10*j + k), i, j, k );
            }
         }
      }
      Console.WriteLine("The elements of the array are:");
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++)
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++)
         {
             for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               Console.Write("{0, 3} ", ary.GetValue(i, j, k));
            }
            Console.WriteLine();
         }
         Console.WriteLine();
      }
   }
}
   

The output is

The elements of the array are:
  0   1   2
 10  11  12
 20  21  22
 30  31  32

100 101 102
110 111 112
120 121 122
130 131 132
 

public static System.Array CreateInstance(System.Type elementType, System.Int32 length1, System.Int32 length2)

Creates a zero-based, two-dimensional array of the specified System.Type and dimension lengths.

Parameter elementType: The System.Type of the elements contained in the new System.Array instance.

Parameter length1: A System.Int32 that contains the number of elements contained in the first dimension of the new System.Array instance.

Parameter length2: A System.Int32 that contains the number of elements contained in the second dimension of the new System.Array instance.

Returns: A new zero-indexed, two-dimensional System.Array instance of elementType objects with the size length1 for the first dimension and length2 for the second.

Throws: System.ArgumentNullException: elementType is null.

Throws: System.ArgumentException: elementType is not a valid System.Type.

Throws: System.ArgumentOutOfRangeException: length1 < 0. -or- length2 < 0.

Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. Unlike most classes, System.Array provides the System.Array.CreateInstance(System.Type,System.Int32) method, instead of public constructors, to allow for late bound access.

Example:

The following example shows how to create and initialize a two-dimensional System.Array.


using System;

public class Create2DArrayExample
{
   public static void Main()
   {
      int i, j;
      Array ary = Array.CreateInstance( typeof(int), 5, 3 );
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++ )
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++ )
         {
            ary.SetValue( (10*i + j), i, j );
         }
      }
      Console.WriteLine("The elements of the array are:");
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++)
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++)
         {
            Console.Write("{0, 2} ", ary.GetValue(i, j));
         }
         Console.WriteLine();
      }
   }
} 
  

The output is

The elements of the array are:
 0  1  2
10 11 12
20 21 22
30 31 32
40 41 42
 

public static System.Array CreateInstance(System.Type elementType, System.Int32 length)

Constructs a zero-based, one-dimensional array with the specified number of elements of the specified type.

Parameter elementType: The System.Type of the elements contained in the new System.Array instance.

Parameter length: A System.Int32 that contains the number of elements contained in the new System.Array instance.

Returns: A zero-based, one-dimensional System.Array object containing length elements of type elementType.

Throws: System.ArgumentNullException: elementType is null.

Throws: System.ArgumentException: elementType is not a valid System.Type.

Throws: System.ArgumentOutOfRangeException: length < 0.

Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. Unlike most classes, System.Array provides the System.Array.CreateInstance(System.Type,System.Int32) method, instead of public constructors, to allow for late bound access.

Example:

The following example shows how to create and initialize a one-dimensional System.Array.

using System;

public class ArrayCreateInstanceExample
{

   public static void Main()
   {

      Array intAry = Array.CreateInstance(typeof(int),5);
      for (int i=intAry.GetLowerBound(0);i<=intAry.GetUpperBound(0);i++)
         intAry.SetValue(i*3,i);
      Console.Write("The values of the array are:");
      foreach (int i in intAry)
         Console.Write("{0} ",i);
   
   }

}
   

The output is

The values of the array are: 0 3 6 9 12

public static System.Array CreateInstance(System.Type elementType, System.Int32[] lengths, System.Int32[] lowerBounds)

Creates a multidimensional array of the specified System.Type and dimension lengths, with the specified lower bounds.

Parameter elementType: The System.Type of the elements contained in the new System.Array instance.

Parameter lengths: A one-dimensional array of System.Int32 objects that contains the size of each dimension of the new System.Array instance.

Parameter lowerBounds: A one-dimensional array of System.Int32 objects that contains the lower bound of each dimension of the new System.Array instance.

Returns: A new multidimensional System.Array of the specified System.Type with the specified length and lower bound for each dimension.

Throws: System.ArgumentNullException: elementType, lengths, or lowerBounds is null.

Throws: System.ArgumentException: elementType is not a valid System.Type. -or- lengths.Length = 0. -or- lengths and lowerBounds do not contain the same number of elements.

Throws: System.ArgumentOutOfRangeException: A value in lengths is less than zero.

The lengths and lowerBounds are required to have the same number of elements. The number of elements in lengths equals the number of dimensions in the new System.Array instance Each element of lengths specifies the length of the corresponding dimension in the new System.Array instance. Each element of lowerBounds specifies the lower bound of the corresponding dimension in the new System.Array instance. Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. Unlike most classes, System.Array provides the System.Array.CreateInstance(System.Type,System.Int32) method, instead of public constructors, to allow for late bound access.

Example:

The following example shows how to create and initialize a multidimensional System.Array with specified low bounds.


using System;

public class MultiDimNonZeroBoundExample
{
   public static void Main()
   {
      int i, j, k;
      int[] indexAry = {4, 2, 3};
      int[] lowboundAry = {3, 2, 1};
      Array ary = Array.CreateInstance( typeof(int), indexAry, lowboundAry );
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++ )
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++ )
         {
            for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               ary.SetValue( (100*i + 10*j + k), i, j, k );
            }
         }
      }
      Console.WriteLine("The elements of the array are:");
      for( i = ary.GetLowerBound(0); i <= ary.GetUpperBound(0); i++)
      {
         for( j = ary.GetLowerBound(1); j <= ary.GetUpperBound(1); j++)
         {
             for( k = ary.GetLowerBound(2); k <= ary.GetUpperBound(2); k++ )
            {
               Console.Write("{0, 3} ", ary.GetValue(i, j, k));
            }
            Console.WriteLine();
         }
         Console.WriteLine();
      }
   }
}
   

The output is

The elements of the array are:
321 322 323
331 332 333

421 422 423
431 432 433

521 522 523
531 532 533

621 622 623
631 632 633

public virtual System.Collections.IEnumerator GetEnumerator()

Returns a System.Collections.IEnumerator for the current instance.

Returns: A System.Collections.IEnumerator for the current instance.

A System.Collections.IEnumerator grants read-access to the elements of a System.Array. This method is implemented to support the System.Collections.IEnumerator interface. For more information regarding the use of an enumerator, see System.Collections.IEnumerator. Initially, the enumerator is positioned before the first element of the current instance. System.Collections.IEnumerator.Reset returns the enumerator to this position. Therefore, after an enumerator is created or after a System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.MoveNext is required to be called to advance the enumerator to the first element of the collection before reading the value of System.Collections.IEnumerator.Current. The enumerator is in an invalid state if it is positioned before the first element or after the last element of the current instance. Whenever the enumerator is in an invalid state, a call to System.Collections.IEnumerator.Current is required to throw a System.InvalidOperationException. System.Collections.IEnumerator.Current returns the same object until either System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called. Once the enumerator of the current instance is moved immediately past the last element of the current instance, subsequent calls to System.Collections.IEnumerator.MoveNext return false and the enumerator remains positioned immediately past the last element. Multidimensional arrays will be processed in Row-major form. For some multidimensional System.Array objects, it may be desirable for an enumerator to process them in Column-major form. Override this method to provide read-access to the current instance. Use this method to iterate over the elements of the current instance.

Example:

This example demonstrates the System.Array.GetEnumerator method.

using System;
using System.Collections;
public class ArrayGetEnumerator {
   public static void Main() {
      string[,] strAry = {{"1","one"}, {"2", "two"}, {"3", "three"}};
      Console.Write( "The elements of the array are: " );
      IEnumerator sEnum = strAry.GetEnumerator();
      while ( sEnum.MoveNext() )
         Console.Write( " {0}", sEnum.Current );
   }
}
   

The output is

The elements of the array are: 1 one 2 two 3 three

public System.Int32 GetLowerBound(System.Int32 dimension)

Returns the lower bound of the specified dimension in the current instance.

Parameter dimension: A System.Int32 that contains the zero-based dimension of the current instance whose lower bound is to be determined.

Returns: A System.Int32 that contains the lower bound of the specified dimension in the current instance.

Throws: System.IndexOutOfRangeException: dimension < 0. -or- dimension is equal to or greater than the System.Array.Rank property of the current instance.

For example, System.Array.GetLowerBound(System.Int32) (0) returns the lower bound of the first dimension of the current instance, and System.Array.GetLowerBound(System.Int32)(System.Array.Rank - 1) returns the lower bound of the last dimension of the current instance.

public System.Int32 GetUpperBound(System.Int32 dimension)

Returns the upper bound of the specified dimension in the current instance.

Parameter dimension: A System.Int32 that contains the zero-based dimension of the current instance whose upper bound is to be determined.

Returns: A System.Int32 that contains the upper bound of the specified dimension in the current instance.

Throws: System.IndexOutOfRangeException: dimension < 0. -or- dimension is equal to or greater than the System.Array.Rank property of the current instance.

For example, System.Array.GetUpperBound(System.Int32) (0) returns the upper bound of the first dimension of the current instance, and System.Array.GetUpperBound(System.Int32)(System.Array.Rank - 1) returns the upper bound of the last dimension of the current instance.

public System.Object GetValue(System.Int32[] indices)

Gets the value at the specified position in the current multidimensional instance.

Parameter indices: A one-dimensional array of System.Int32 objects that contains the indices that specify the position of the element in the current instance whose value to get.

Returns: A System.Object that contains the value at the specified position in the current instance.

Throws: System.ArgumentNullException: indices is null.

Throws: System.ArgumentException: The number of dimensions in the current instance is not equal to the number of elements in indices.

Throws: System.IndexOutOfRangeException: At least one element in indices is outside the range of valid indices for the corresponding dimension of the current instance.

The number of elements in indices is required to be equal to the number of dimensions in the current instance. All elements in indices collectively specify the position of the desired element in the current instance. Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the values in indices are out of bounds.

public System.Object GetValue(System.Int32 index)

Gets the value at the specified position in the current one-dimensional instance.

Parameter index: A System.Int32 that contains the position of the value to get from the current instance.

Returns: A System.Object that contains the value at the specified position in the current instance.

Throws: System.ArgumentException: The current instance has more than one dimension.

Throws: System.IndexOutOfRangeException: index is outside the range of valid indices for the current instance.

Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether index is out of bounds.

Example:

This example demonstrates the System.Array.GetValue(System.Int32[]) method.

using System;
public class ArrayGetValueExample {
   public static void Main() {
      String[] strAry = { "one", "two", "three", "four", "five" };
      Console.Write( "The elements of the array are: " );
      for( int i = 0; i < strAry.Length; i++ )
         Console.Write( " '{0}' ", strAry.GetValue( i ) );
   }
}
   

The output is

The elements of the array are: 'one' 'two' 'three' 'four' 'five'

public System.Object GetValue(System.Int32 index1, System.Int32 index2)

Gets the value at the specified position in the current two-dimensional instance.

Parameter index1: A System.Int32 that contains the first-dimension index of the element in the current instance to get.

Parameter index2: A System.Int32 that contains the second-dimension index of the element in the current instance to get.

Returns: A System.Object that contains the value at the specified position in the current instance.

Throws: System.ArgumentException: The current instance does not have exactly two dimensions.

Throws: System.IndexOutOfRangeException: At least one of index1 or index2 is outside the range of valid indexes for the corresponding dimension of the current instance.

Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the indices are out of bounds.

public System.Object GetValue(System.Int32 index1, System.Int32 index2, System.Int32 index3)

Gets the value at the specified position in the current three-dimensional instance.

Parameter index1: A System.Int32 that contains the first-dimension index of the element in the current instance to get.

Parameter index2: A System.Int32 that contains the second-dimension index of the element in the current instance to get.

Parameter index3: A System.Int32 that contains the third-dimension index of the element in the current instance to get.

Returns: A System.Object that contains the value at the specified position in the current instance.

Throws: System.ArgumentException: The current instance does not have exactly three dimensions.

Throws: System.IndexOutOfRangeException: At least one ofindex1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current instance.

Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the indices are out of bounds.

public static System.Int32 IndexOf(System.Array array, System.Object value, System.Int32 startIndex, System.Int32 count)

Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object in the specified range.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Parameter startIndex: A System.Int32 that contains the index at which searching starts.

Parameter count: A System.Int32 that contains the number of elements to search, beginning with startIndex.

Returns: A System.Int32 containing the index of the first occurrence of value in array, within the range startIndex through startIndex + count- 1, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for the failed search.

Throws: System.ArgumentNullException: array is null.

Throws: System.ArgumentOutOfRangeException: startIndex is outside the range of valid indices for array. -or- count < 0. -or- The sum of count and startIndex does not specify a valid range in array (i.e. count + startIndex > array.GetLowerBound(0) + array.Length).

Throws: System.RankException: array has more than one dimension.

The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

public static System.Int32 IndexOf(System.Array array, System.Object value, System.Int32 startIndex)

Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object between the specified index and the last element.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Parameter startIndex: A System.Int32 that contains the index at which searching starts.

Returns: A System.Int32 containing the index of the first occurrence of value in array, within the range startIndex through the last element of array, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for the failed search.

Throws: System.ArgumentNullException: array is null.

Throws: System.ArgumentOutOfRangeException: startIndex is outside the range of valid indexes for array.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.IndexOf(System.Array,System.Object) is equivalent to System.Array.IndexOf(System.Array,System.Object) (array, value , startIndex, (array.Length - startIndex+array.GetLowerBound(0))). The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

public static System.Int32 IndexOf(System.Array array, System.Object value)

Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Returns: A System.Int32 containing the index of the first occurrence of value in array, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for a failed search.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.IndexOf(System.Array,System.Object) is equivalent to System.Array.IndexOf(System.Array,System.Object)(array, value, array.GetLowerBound(0),array.Length). The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

Example:

The following example demonstrates the System.Array.IndexOf(System.Array,System.Object) method.

using System;
public class ArrayIndexOfExample {
   public static void Main() {
      int[] intAry = { 0, 1, 2, 0, 1 };
      Console.Write( "The values of the array are: " );
      foreach( int i in intAry )
         Console.Write( "{0,5}", i );
      Console.WriteLine();
      int j = Array.IndexOf( intAry, 1 );
      Console.WriteLine( "The first occurrence of 1 is at index {0}", j );
   }
}

The output is

The values of the array are: 0 1 2 0 1

The first occurrence of 1 is at index 1

public System.Void Initialize()

Initializes every element of the current instance of value-type objects by calling the default constructor of that value type.

This method cannot be used on reference-type arrays. If the current instance is not a value-type System.Array or if the value type does not have a default constructor, the current instance is not modified. The current instance can have any lower bound and any number of dimensions. This method can be used only on value types that have constructors.

public static System.Int32 LastIndexOf(System.Array array, System.Object value, System.Int32 startIndex, System.Int32 count)

Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object in the specified range.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Parameter startIndex: A System.Int32 that contains the index at which searching starts.

Parameter count: A System.Int32 that contains the number of elements to search, beginning with startIndex .

Returns: A System.Int32 containing the index of the last occurrence of value in array, within the range startIndex through startIndex-count+ 1, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for the failed search.

Throws: System.ArgumentNullException: array is null.

Throws: System.ArgumentOutOfRangeException: startIndex is outside the range of valid indices for array. -or- count < 0. -or- count and startIndex do not specify a valid range in array.

Throws: System.RankException: array has more than one dimension.

The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

public static System.Int32 LastIndexOf(System.Array array, System.Object value, System.Int32 startIndex)

Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object between the specified index and the first element.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Parameter startIndex: A System.Int32 that contains the index at which searching starts.

Returns: A System.Int32 containing the index of the last occurrence of value in the range startIndex through the lower bound of array, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for the failed search.

Throws: System.ArgumentNullException: array is null.

Throws: System.ArgumentOutOfRangeException: startIndex is outside the range of valid indices for array.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.LastIndexOf(System.Array,System.Object) is equivalent to System.Array.LastIndexOf(System.Array,System.Object)( array, value, startIndex,startIndex+ 1 -array.GetLowerBound(0)). The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

public static System.Int32 LastIndexOf(System.Array array, System.Object value)

Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object.

Parameter array: A one-dimensional System.Array to search.

Parameter value: A System.Object to locate in array.

Returns: A System.Int32 containing the index of the last occurrence in array of value, if found; otherwise, array.GetLowerBound(0) - 1. For a vector, if value is not found, the return value will be -1. This provides the caller with a standard code for the failed search.

Throws: System.ArgumentNullException: array is null .

Throws: System.RankException: array has more than one dimension.

This version of System.Array.LastIndexOf(System.Array,System.Object) is equivalent to System.Array.LastIndexOf(System.Array,System.Object)(array, value, (array.GetLowerBound(0) + array.Length - 1), array.Length). The elements will be compared using the semantics of the System.Object.Equals(System.Object) method. For user-defined types, System.Object.Equals(System.Object) is actually called.

Example:

The following example demonstrates the System.Array.LastIndexOf(System.Array,System.Object) method.

using System;

public class ArrayLastIndexOfExample {

   public static void Main() {
      int[] intAry = { 0, 1, 2, 0, 1 };
      Console.Write( "The values of the array are: ");
      foreach( int i in intAry )
         Console.Write( "{0,5}", i );
      Console.WriteLine();
      int j = Array.LastIndexOf( intAry, 1 );
      Console.WriteLine( "The last occurrence of 1 is at index {0}", j );
   }
}

The output is

The values of the array are: 0 1 2 0 1

The last occurrence of 1 is at index 4

public static System.Void Reverse(System.Array array, System.Int32 index, System.Int32 length)

Reverses the sequence of the elements in the specified range of the specified one-dimensional System.Array.

Parameter array: The one-dimensional System.Array to reverse.

Parameter index: A System.Int32 that contains the index at which reversing starts.

Parameter length: A System.Int32 that contains the number of elements to reverse.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array is multidimensional.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). length < 0.

Throws: System.ArgumentException: index and length do not specify a valid range in array (i.e. index + length > array.GetLowerBound(0) + array.Length).

Example:

The following example demonstrates the System.Array.Reverse(System.Array) method.

using System;
public class ArrayReverseExample {
   public static void Main() {
      string[] strAry = { "one", "two", "three" };
      Console.Write( "The elements of the array are:");
      foreach( string str in strAry )
         Console.Write( " {0}", str );
      Array.Reverse( strAry );
      Console.WriteLine();
      Console.WriteLine( "After reversing the array," );
      Console.Write( "the elements of the array are:");
      foreach( string str in strAry )
         Console.Write( " {0}", str );
   }
}

The output is

The elements of the array are: one two three

After reversing the array,

the elements of the array are: three two one

public static System.Void Reverse(System.Array array)

Reverses the sequence of the elements in the specified one-dimensional System.Array.

Parameter array: The one-dimensional System.Array to reverse.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

This version of System.Array.Reverse(System.Array) is equivalent to System.Array.Reverse(System.Array)(array, array.GetLowerBound(0), array.Length).

public System.Void SetValue(System.Object value, System.Int32 index)

Sets the value of the element at the specified position in the current one-dimensional instance.

Parameter value: A System.Object that contains the new value for the specified element.

Parameter index: A System.Int32 that contains the index of the element whose value is to be set.

Throws: System.ArgumentException: The current instance has more than one dimension. -or- value is not assignment-compatible with the element type of the current instance.

Throws: System.IndexOutOfRangeException: index is outside the range of valid indices for the current instance.

Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether index is out of bounds. For more information regarding valid conversions that will be performed by this method, see System.Convert.

public System.Void SetValue(System.Object value, System.Int32 index1, System.Int32 index2)

Sets the value of the element at the specified position in the current two-dimensional instance.

Parameter value: A System.Object that contains the new value for the specified element.

Parameter index1: A System.Int32 that contains the first-dimension index of the element in the current instance to set.

Parameter index2: A System.Int32 that contains the second-dimension index of the element in the current instance to set.

Throws: System.ArgumentException: The current instance does not have exactly two dimensions. -or- value is not assignment-compatible with the element type of the current instance.

Throws: System.IndexOutOfRangeException: At least one of index1 or index2 is outside the range of valid indices for the corresponding dimension of the current instance.

For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the indices are out of bounds.

public System.Void SetValue(System.Object value, System.Int32 index1, System.Int32 index2, System.Int32 index3)

Sets the value of the element at the specified position in the current three-dimensional instance.

Parameter value: A System.Object that contains the new value for the specified element.

Parameter index1: A System.Int32 that contains the first-dimension index of the element in the current instance to set.

Parameter index2: A System.Int32 that contains the second-dimension index of the element in the current instance to set.

Parameter index3: A System.Int32 that contains the third-dimension index of the element in the current instance to set.

Throws: System.ArgumentException: The current instance does not have exactly three dimensions. -or- value is not assignment-compatible with the element type of the current instance.

Throws: System.IndexOutOfRangeException: At least one of index1, index2, or index3 is outside the range of valid indices for the corresponding dimension of the current instance.

For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the indices are out of bounds.

public System.Void SetValue(System.Object value, System.Int32[] indices)

Sets the value of the element at the specified position in the current multidimensional instance.

Parameter value: A System.Object that contains the new value for the specified element.

Parameter indices: A one-dimensional array of System.Int32 objects that contains the indices that specify the position of the element in the current instance to set.

Throws: System.ArgumentNullException: indices is null.

Throws: System.ArgumentException: The number of dimensions in the current instance is not equal to the number of elements in indices. -or- value is not assignment-compatible with the element type of the current instance.

Throws: System.IndexOutOfRangeException: At least one element in indices is outside the range of valid indices for the corresponding dimension of the current instance.

The number of elements in indices is required to be equal to the number of dimensions in the current instance. All elements in indices collectively specify the position of the desired element in the current instance. For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound(System.Int32) and System.Array.GetUpperBound(System.Int32) methods to determine whether any of the values in indices is out of bounds.

public static System.Void Sort(System.Array keys, System.Array items, System.Int32 index, System.Int32 length, System.Collections.IComparer comparer)

Sorts the specified range of the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array using the specified System.Collections.IComparer implementation.

Parameter keys: A one-dimensional System.Array that contains the keys to sort.

Parameter items: A one-dimensional System.Array that contains the items that correspond to each element of keys. Specify a null reference to sort only keys.

Parameter index: A System.Int32 that contains the index at which sorting starts.

Parameter length: A System.Int32 that contains the number of elements to sort.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Throws: System.ArgumentNullException: keys is null.

Throws: System.RankException: keys has more than one dimension. -or- items is not a null reference and has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < keys.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -or- index and length do not specify a valid range in key. -or- items is not a null reference, and index and length do not specify a valid range in items. -or- comparer is a null reference, and one or more elements in keys do not implement the System.IComparable interface.

Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys. After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items will be sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are undefined. If comparer is a null reference, each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.

public static System.Void Sort(System.Array array, System.Int32 index, System.Int32 length, System.Collections.IComparer comparer)

Sorts the elements in the specified section of the specified one-dimensional System.Array using the specified System.Collections.IComparer implementation.

Parameter array: A one-dimensional System.Array to sort.

Parameter index: A System.Int32 that contains the index at which sorting starts.

Parameter length: A System.Int32 that contains the number of elements to sort.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: index and length do not specify a valid range in array. -or- comparer is a null reference, and one or more elements in array do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(array, null, index, length, comparer). If comparer is a null reference, each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified.

public static System.Void Sort(System.Array keys, System.Array items, System.Collections.IComparer comparer)

Sorts the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array using the specified System.Collections.IComparer implementation.

Parameter keys: A one-dimensional System.Array that contains the keys to sort.

Parameter items: A one-dimensional System.Array that contains the items that correspond to each element in keys. Specify a null reference to sort only keys.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Throws: System.ArgumentNullException: keys is null.

Throws: System.RankException: keys has more than one dimension. -or- items is not a null reference and has more than one dimension.

Throws: System.ArgumentException: items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -or- items is not a null reference, and keys.Length > items.Length. -or- comparer is a null reference, and one or more elements in the keys do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(keys, items, keys.GetLowerBound(0), keys.Length, comparer). Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys . After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items are sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are unspecified. If comparer is a null reference, each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.

public static System.Void Sort(System.Array array, System.Collections.IComparer comparer)

Sorts the elements in the specified one-dimensional System.Array using the specified System.Collections.IComparer implementation.

Parameter array: The one-dimensional System.Array to sort.

Parameter comparer: The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentException: comparer is a null reference, and one or more elements in array do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(array, null, array.GetLowerBound(0), array.Length, comparer). If comparer is a null reference, each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified.

public static System.Void Sort(System.Array keys, System.Array items, System.Int32 index, System.Int32 length)

Sorts the specified ranges of the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array.

Parameter keys: A one-dimensional System.Array that contains the keys to sort.

Parameter items: A one-dimensional System.Array that contains the items that correspond to each element in keys. Specify a null reference to sort only keys.

Parameter index: A System.Int32 that contains the index at which sort begins.

Parameter length: A System.Int32 that contains the number of elements to sort.

Throws: System.ArgumentNullException: keys is null.

Throws: System.RankException: keys has more than one dimension. -or- items is not a null reference and has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < keys.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -or- index and length do not specify a valid range in key. -or- items is not a null reference, and index and length do not specify a valid range in items. -or- One or more elements in keys do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(keys, items, index, length, null). Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys . After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are undefined. Each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.

public static System.Void Sort(System.Array array)

Sorts the elements of the specified one-dimensional System.Array.

Parameter array: A one-dimensional System.Array to sort.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentException: One or more elements in array do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(array, null, array.GetLowerBound(0), array.Length, null). Each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array.

Example:

This example demonstrates the System.Array.Sort(System.Array) method.

using System;
public class ArraySortExample {
   public static void Main() {
      string[] strAry = { "All's", "well", "that", "ends", "well" };
      Console.Write( "The original string array is: " );
      foreach ( String str in strAry )
         Console.Write( str + " " );
      Console.WriteLine();
      Array.Sort( strAry );
      Console.Write( "The sorted string array is: " );
      foreach ( string str in strAry )
         Console.Write( str + " " );
   }
}

The output is

The original string array is: All's well that ends well

The sorted string array is: All's ends that well well

public static System.Void Sort(System.Array keys, System.Array items)

Sorts the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array.

Parameter keys: A one-dimensional System.Array that contains the keys to sort.

Parameter items: A one-dimensional System.Array that contains the items that correspond to each of element of keys. Specify a null reference to sort only keys.

Throws: System.ArgumentNullException: keys is null.

Throws: System.RankException: keys has more than one dimension. -or- items is not a null reference and has more than one dimension.

Throws: System.ArgumentException: items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -or- items is not a null reference, and keys.Length > items.Length. -or- One or more elements in keys do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(keys, items, keys.GetLowerBound(0), keys.Length, null). Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys . After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items are sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are unspecified. Each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.

Example:

This example demonstrates the System.Array.Sort(System.Array) method.

using System;
public class ArraySortExample {
   public static void Main() {
      string[] strAry = { "All's", "well", "that", "ends", "well" };
      int[] intAry = { 3, 4, 0, 1, 2 };
      Console.Write( "The original string array is: " );
      foreach ( string str in strAry )
         Console.Write( str + " " );
      Console.WriteLine();
      Console.Write( "The key array is: " );
      foreach ( int i in intAry )
         Console.Write( i + " " );
      Console.WriteLine();
      Array.Sort( intAry, strAry );
      Console.Write( "The sorted string array is: " );
      foreach ( string str in strAry )
         Console.Write( str + " " );
   }
}

The output is

The original string array is: All's well that ends well

The key array is: 3 4 0 1 2

The sorted string array is: that ends well All's well

public static System.Void Sort(System.Array array, System.Int32 index, System.Int32 length)

Sorts the elements in the specified range of the specified one-dimensional System.Array.

Parameter array: A one-dimensional System.Array to sort.

Parameter index: A System.Int32 that contains the index at which sorting starts.

Parameter length: A System.Int32 that contains the number of elements to sort.

Throws: System.ArgumentNullException: array is null.

Throws: System.RankException: array has more than one dimension.

Throws: System.ArgumentOutOfRangeException: index < array.GetLowerBound(0). -or- length < 0.

Throws: System.ArgumentException: index and length do not specify a valid range in array. -or- One or more elements in array do not implement the System.IComparable interface.

This version of System.Array.Sort(System.Array) is equivalent to System.Array.Sort(System.Array)(array, null , index, length, null). Each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified.

public System.Int32 System.Collections.IList.Add(System.Object value)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Add.]

public System.Void System.Collections.IList.Clear()

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Clear.]

public System.Boolean System.Collections.IList.Contains(System.Object value)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Contains.]

public System.Int32 System.Collections.IList.IndexOf(System.Object value)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.IndexOf.]

public System.Void System.Collections.IList.Insert(System.Int32 index, System.Object value)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Insert.]

public System.Void System.Collections.IList.Remove(System.Object value)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Remove.]

public System.Void System.Collections.IList.RemoveAt(System.Int32 index)

Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.RemoveAt.]

Functions inherited from System.Object:

public virtual System.Boolean Equals(System.Object obj)

Determines whether the specified System.Object is equal to the current instance.

Parameter obj: The System.Object to compare with the current instance.

Returns: true if obj is equal to the current instance; otherwise, false.

The statements listed below are required to be true for all implementations of the System.Object.Equals(System.Object) method. In the list, x, y, and z represent non-null object references. See System.Object.GetHashCode for additional required behaviors pertaining to the System.Object.Equals(System.Object) method. Implementations of System.Object.Equals(System.Object) should not throw exceptions. The System.Object.Equals(System.Object) method tests for referential equality , which means that System.Object.Equals(System.Object) returns true if the specified instance of Object and the current instance are the same instance; otherwise, it returns false . An implementation of the System.Object.Equals(System.Object) method is shown in the following C# code: public virtual bool Equals(Object obj) { return this == obj; } For some kinds of objects, it is desirable to have System.Object.Equals(System.Object) test for value equality instead of referential equality. Such implementations of Equals return true if the two objects have the same "value", even if they are not the same instance. The definition of what constitutes an object's "value" is up to the implementer of the type, but it is typically some or all of the data stored in the instance variables of the object. For example, the value of a System.String is based on the characters of the string; the Equals method of the System.String class returns true for any two string instances that contain exactly the same characters in the same order. When the Equals method of a base class provides value equality, an override of Equals in a class derived from that base class should invoke the inherited implementation of Equals . It is recommended (but not required) that types overriding System.Object.Equals(System.Object) also override System.Object.GetHashCode. Hashtables cannot be relied on to work correctly if this recommendation is not followed. If your programming language supports operator overloading, and if you choose to overload the equality operator for a given type, that type should override the Equals method. Such implementations of the Equals method should return the same results as the equality operator. Following this guideline will help ensure that class library code using Equals (such as System.Collections.ArrayList and System.Collections.Hashtable ) behaves in a manner that is consistent with the way the equality operator is used by application code. If you are implementing a value type, you should follow these guidelines: For reference types, the guidelines are as follows: If you implement System.IComparable on a given type, you should override Equals on that type. The System.Object.Equals(System.Object) method is called by methods in collections classes that perform search operations, including the System.Array.IndexOf(System.Array,System.Object) method and the System.Collections.ArrayList.Contains(System.Object) method.

Example:

Example 1:

The following example contains two calls to the default implementation of System.Object.Equals(System.Object) .

using System;
class MyClass {
   static void Main() {
      Object obj1 = new Object();
      Object obj2 = new Object();
      Console.WriteLine(obj1.Equals(obj2));
      obj1 = obj2; 
      Console.WriteLine(obj1.Equals(obj2)); 
   }
}

The output is

False

True

Example 2:

The following example shows a Point class that overrides the System.Object.Equals(System.Object) method to provide value equality and a class Point3D, which is derived from Point . Because Point's override of System.Object.Equals(System.Object) is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from System.Object and checks for referential equality) is not invoked. However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality.

using System;
public class Point: object {
 int x, y;
 public override bool Equals(Object obj) {
 //Check for null and compare run-time types.
 if (obj == null || GetType() != obj.GetType()) return false;
 Point p = (Point)obj;
 return (x == p.x) && (y == p.y);
 }
 public override int GetHashCode() {
 return x ^ y;
 }
}

class Point3D: Point {
 int z;
 public override bool Equals(Object obj) {
 return base.Equals(obj) && z == ((Point3D)obj).z;
 }
 public override int GetHashCode() {
 return base.GetHashCode() ^ z;
 }
}

The Point.Equals method checks that the obj argument is non-null and that it references an instance of the same type as this object. If either of those checks fail, the method returns false. The System.Object.Equals(System.Object) method uses System.Object.GetType to determine whether the run-time types of the two objects are identical. (Note that typeof is not used here because it returns the static type.) If instead the method had used a check of the form

<doc:param name="obj"/>
is Point , the check would return true in cases where obj is an instance of a subclass of Point , even though obj and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts obj to type Point and returns the result of comparing the instance variables of the two objects.

In Point3D.Equals , the inherited Equals method is invoked before anything else is done; the inherited Equals method checks to see that obj is non-null, that obj is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Equals returns true does the method compare the instance variables introduced in the subclass. Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a subclass of Point3D .

Example 3:

In the previous example, operator == (the equality operator) is used to compare the individual instance variables. In some cases, it is appropriate to use the System.Object.Equals(System.Object) method to compare instance variables in an Equals implementation, as shown in the following example:

using System;
class Rectangle {
 Point a, b;
 public override bool Equals(Object obj) {
 if (obj == null || GetType() != obj.GetType()) return false;
 Rectangle r = (Rectangle)obj;
 //Use Equals to compare instance variables
 return a.Equals(r.a) && b.Equals(r.b);
 }
 public override int GetHashCode() {
 return a.GetHashCode() ^ b.GetHashCode();
 }
}

Example 4:

In some languages, such as C#, operator overloading is supported. When a type overloads operator ==, it should also override the System.Object.Equals(System.Object) method to provide the same functionality. This is typically accomplished by writing the Equals method in terms of the overloaded operator ==. For example:

using System;
public struct Complex {
 double re, im;
 public override bool Equals(Object obj) {
 return obj is Complex && this == (Complex)obj;
 }
 public override int GetHashCode() {
 return re.GetHashCode() ^ im.GetHashCode();
 }
 public static bool operator ==(Complex x, Complex y) {
 return x.re == y.re && x.im == y.im;
 }
 public static bool operator !=(Complex x, Complex y) {
 return !(x == y);
 }
}

Because Complex is a C# struct (a value type), it is known that there will be no subclasses of Complex . Therefore, the System.Object.Equals(System.Object) method need not compare the GetType() results for each object, but can instead use the is operator to check the type of the obj parameter.

public static System.Boolean Equals(System.Object objA, System.Object objB)

Determines whether two object references are equal.

Parameter objA: First object to compare.

Parameter objB: Second object to compare.

Returns: true if one or more of the following statements is true: otherwise returns false.

This static method checks for null references before it calls objA.Equals(objB ) and returns false if either objA or objB is null. If the Equals(object obj) implementation throws an exception, this method throws an exception.

Example:

The following example demonstrates the System.Object.Equals(System.Object) method.

using System;

public class MyClass {
   public static void Main() {
   string s1 = "Tom";
   string s2 = "Carol";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = "Tom";
   s2 = "Tom";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = "Tom";
   Console.WriteLine("Object.Equals(null, \"{1}\") => {2}",
       s1, s2, Object.Equals(s1, s2));

   s1 = "Carol";
   s2 = null;
   Console.WriteLine("Object.Equals(\"{0}\", null) => {2}", 
       s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = null;
   Console.WriteLine("Object.Equals(null, null) => {2}", 
       s1, s2, Object.Equals(s1, s2));
   }
}
   

The output is

Object.Equals("Tom", "Carol") => False

Object.Equals("Tom", "Tom") => True

Object.Equals(null, "Tom") => False

Object.Equals("Carol", null) => False

Object.Equals(null, null) => True

public System.Void Finalize()

Allows a System.Object to perform cleanup operations before the memory allocated for the System.Object is automatically reclaimed.

During execution, System.Object.Finalize is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to System.GC.SuppressFinalize(System.Object). During shutdown of an application domain, System.Object.Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. System.Object.Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object) has not been subsequently called. Conforming implementations of the CLI are required to make every effort to ensure that for every object that has not been exempted from finalization, the System.Object.Finalize method is called after the object becomes inaccessible. However, there may be some circumstances under which Finalize is not called. Conforming CLI implementations are required to explicitly specify the conditions under which Finalize is not guaranteed to be called. For example, Finalize might not be guaranteed to be called in the event of equipment failure, power failure, or other catastrophic system failures. In addition to System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object), conforming implementations of the CLI are allowed to provide other mechanisms that affect the behavior of System.Object.Finalize . Any mechanisms provided are required to be specified by the CLI implementation. The order in which the Finalize methods of two objects are run is unspecified, even if one object refers to the other. The thread on which Finalize is run is unspecified. Every implementation of System.Object.Finalize in a derived type is required to call its base type's implementation of Finalize . This is the only case in which application code calls System.Object.Finalize . The System.Object.Finalize implementation does nothing. A type should implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. Because Finalize methods may be invoked in any order (including from multiple threads), synchronization may be necessary if the Finalize method may interact with other objects, whether accessible or not. Furthermore, since the order in which Finalize is called is unspecified, implementers of Finalize (or of destructors implemented through overriding Finalize) must take care to correctly handle references to other objects, as their Finalize method may already have been invoked. In general, referenced objects should not be considered valid during finalization. See the System.IDisposable interface for an alternate means of disposing of resources. For C# developers: Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, System.Object.Finalize cannot be called or overridden.

public virtual System.Int32 GetHashCode()

Generates a hash code for the current instance.

Returns: A System.Int32 containing the hash code for the current instance.

System.Object.GetHashCode serves as a hash function for a specific type. A hash function is used to quickly generate a number (a hash code) corresponding to the value of an object. Hash functions are used with hashtables. A good hash function algorithm rarely generates hash codes that collide. For more information about hash functions, see The Art of Computer Programming , Vol. 3, by Donald E. Knuth. All implementations of System.Object.GetHashCode are required to ensure that for any two object references x and y, if x.Equals(y) == true, then x.GetHashCode() == y.GetHashCode(). Hash codes generated by System.Object.GetHashCode need not be unique. Implementations of System.Object.GetHashCode are not permitted to throw exceptions. The System.Object.GetHashCode implementation attempts to produce a unique hash code for every object, but the hash codes generated by this method are not guaranteed to be unique. Therefore, System.Object.GetHashCode may generate the same hash code for two different instances. It is recommended (but not required) that types overriding System.Object.GetHashCode also override System.Object.Equals(System.Object) . Hashtables cannot be relied on to work correctly if this recommendation is not followed. Use this method to obtain the hash code of an object. Hash codes should not be persisted (i.e. in a database or file) as they are allowed to change from run to run.

Example:

Example 1

In some cases, System.Object.GetHashCode is implemented to simply return an integer value. The following example illustrates an implementation of System.Int32.GetHashCode , which returns an integer value:

using System;
public struct Int32 {
 int value;
 //other methods...

 public override int GetHashCode() {
 return value;
 }
}

Example 2

Frequently, a type has multiple data members that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an xor (exclusive or) operation, as shown in the following example:

using System;
public struct Point {
 int x;
 int y; 
 //other methods
 
 public override int GetHashCode() {
 return x ^ y;
 }
}

Example 3

The following example illustrates another case where the type's fields are combined using xor (exclusive or) to generate the hash code. Notice that in this example, the fields represent user-defined types, each of which implements System.Object.GetHashCode (and should implement System.Object.Equals(System.Object) as well):

using System;
public class SomeType {
 public override int GetHashCode() {
 return 0;
 }
}

public class AnotherType {
 public override int GetHashCode() {
 return 1;
 }
}

public class LastType {
 public override int GetHashCode() {
 return 2;
 }
}
public class MyClass {
 SomeType a = new SomeType();
 AnotherType b = new AnotherType();
 LastType c = new LastType();

 public override int GetHashCode () {
 return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
 }
}

Avoid implementing System.Object.GetHashCode in a manner that results in circular references. In other words, if AClass.GetHashCode calls BClass.GetHashCode, it should not be the case that BClass.GetHashCode calls AClass.GetHashCode.

Example 4

In some cases, the data member of the class in which you are implementing System.Object.GetHashCode is bigger than a System.Int32. In such cases, you could combine the high order bits of the value with the low order bits using an XOR operation, as shown in the following example:

using System;
public struct Int64 {
 long value;
 //other methods...

 public override int GetHashCode() {
 return ((int)value ^ (int)(value >> 32));
 }
}

public System.Type GetType()

Gets the type of the current instance.

Returns: The instance of System.Type that represents the run-time type (the exact type) of the current instance.

For two objects x and y that have identical run-time types, System.Object.ReferenceEquals(System.Object,System.Object)(x.GetType(),y.GetType()) returns true .

Example:

The following example demonstrates the fact that System.Object.GetType returns the run-time type of the current instance:

using System;
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
   public static void Main() {
   MyBaseClass myBase = new MyBaseClass();
   MyDerivedClass myDerived = new MyDerivedClass();

   object o = myDerived;
   MyBaseClass b = myDerived;

   Console.WriteLine("mybase: Type is {0}", myBase.GetType());
   Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
   Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
   Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
   }
}

The output is

mybase: Type is MyBaseClass

myDerived: Type is MyDerivedClass

object o = myDerived: Type is MyDerivedClass

MyBaseClass b = myDerived: Type is MyDerivedClass

protected System.Object MemberwiseClone()

Creates a shallow copy of the current instance.

Returns: A shallow copy of the current instance. The run-time type (the exact type) of the returned object is the same as the run-time type of the object that was copied.

System.Object.MemberwiseClone creates a new instance of the same type as the current instance and then copies each of the object's non-static fields in a manner that depends on whether the field is a value type or a reference type. If the field is a value type, a bit-by-bit copy of all the field's bits is performed. If the field is a reference type, only the reference is copied. The algorithm for performing a shallow copy is as follows (in pseudo-code): for each instance field f in this instance if (f is a value type) bitwise copy the field if (f is a reference type) copy the reference end for loop This mechanism is referred to as a shallow copy because it copies rather than clones the non-static fields. Because System.Object.MemberwiseClone implements the above algorithm, for any object, a, the following statements are required to be true: System.Object.MemberwiseClone does not call any of the type's constructors. If System.Object.Equals(System.Object) has been overridden, a.MemberwiseClone().Equals(a) might return false . For an alternate copying mechanism, see System.ICloneable . System.Object.MemberwiseClone is protected (rather than public) to ensure that from verifiable code it is only possible to clone objects of the same class as the one performing the operation (or one of its subclasses). Although cloning an object does not directly open security holes, it does allow an object to be created without running any of its constructors. Since these constructors may establish important invariants, objects created by cloning may not have these invariants established, and this may lead to incorrect program behavior. For example, a constructor might add the new object to a linked list of all objects of this class, and cloning the object would not add the new object to that list -- thus operations that relied on the list to locate all instances would fail to notice the cloned object. By making the method protected, only objects of the same class (or a subclass) can produce a clone and implementers of those classes are (presumably) aware of the appropriate invariants and can arrange for them to be true without necessarily calling a constructor.

Example:

The following example shows a class called MyClass as well as a representation of the instance of MyClass returned by System.Object.MemberwiseClone .

using System;
class MyBaseClass {
   public static string CompanyName = "My Company";
   public int age;
   public string name;
}

class MyDerivedClass: MyBaseClass {

   static void Main() {
   
   //Create an instance of MyDerivedClass
   //and assign values to its fields.
   MyDerivedClass m1 = new MyDerivedClass();
   m1.age = 42;
   m1.name = "Sam";

   //Do a shallow copy of m1
   //and assign it to m2.
   MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
   }
}

A graphical representation of m1 and m2 might look like this


+---------------+

|     42        |                           m1 

+---------------+

|     +---------|-----------------> "Sam" 

+---------------+                    /|\ 

                                      | 

+---------------+                     | 

|     42        |                     |      m2 

+---------------+                     | 

|      +--------|---------------------| 

+---------------+

public static System.Boolean ReferenceEquals(System.Object objA, System.Object objB)

Determines whether two object references are identical.

Parameter objA: First object to compare.

Parameter objB: Second object to compare.

Returns: True if a and b refer to the same object or are both null references; otherwise, false.

This static method provides a way to compare two objects for reference equality. It does not call any user-defined code, including overrides of System.Object.Equals(System.Object) .

Example:

using System;
class MyClass {
   static void Main() {
   object o = null;
   object p = null;
   object q = new Object();
   Console.WriteLine(Object.ReferenceEquals(o, p));
   p = q;
   Console.WriteLine(Object.ReferenceEquals(p, q));
   Console.WriteLine(Object.ReferenceEquals(o, p));
   }
}
   

The output is

True

True

False

public virtual System.String ToString()

Creates and returns a System.String representation of the current instance.

Returns: A System.String representation of the current instance.

System.Object.ToString returns a string whose content is intended to be understood by humans. Where the object contains culture-sensitive data, the string representation returned by System.Object.ToString takes into account the current system culture. For example, for an instance of the System.Double class whose value is zero, the implementation of System.Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user. System.Object.ToString is equivalent to calling System.Object.GetType to obtain the System.Type object for the current instance and then returning the result of calling the System.Object.ToString implementation for that type. The value returned includes the full name of the type. It is recommended, but not required, that System.Object.ToString be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as System.Int32, implement System.Object.ToString so that it returns the string form of the value the object represents. Subclasses that require more control over the formatting of strings than System.Object.ToString provides should implement System.IFormattable, whose System.Object.ToString method uses the culture of the current thread.

Example:

The following example outputs the textual description of the value of an object of type System.Object to the console.

using System;

class MyClass {
   static void Main() {
      object o = new object();
      Console.WriteLine (o.ToString());
   }
}
      

The output is

System.Object


Functions inherited from System.ICloneable:

public System.Object Clone()

Creates a copy of the current instance.

Returns: A System.Object of the same type as the current instance, containing copies of the non-static members of the current instance.

The exact behavior of this method is unspecified. The intent of the method is to provide a mechanism that constructs instances that are copies of the current instance, without regard for class-specific definitions of the term "copy". Use the System.Object.MemberwiseClone method to create a shallow copy of an object. For more information, see System.Object.MemberwiseClone . This method is required to return an instance of the same type as the current instance. Implement this method to provide class-specific copying behavior. Use the System.ICloneable.Clone method to obtain a copy of the current instance.

Example:

The following example shows an implementation of System.ICloneable.Clone that uses the System.Object.MemberwiseClone method to create a copy of the current instance.

using System;
class MyClass :ICloneable {
    public int myField;
    public MyClass() {
        myField = 0;
    }
    public MyClass(int value) {
        myField = value;
    }
    public object Clone() {
        return this.MemberwiseClone();
    }
}
public class TestMyClass {
    public static void Main() {
        MyClass my1 = new MyClass(44);
        MyClass my2 = (MyClass) my1.Clone();
        Console.WriteLine("my1 {0} my2 {1}",my1.myField, my2.myField);
        my2.myField = 22;
        Console.WriteLine("my1 {0} my2 {1}",my1.myField, my2.myField);
    }
}

The output is

my1 44 my2 44

my1 44 my2 22


Functions inherited from System.Collections.IList:

public System.Int32 Add(System.Object value)

Adds an item to the current instance.

Parameter value: The System.Object to add to the current instance.

Returns: A System.Int32 containing the index of the current instance into which the new element was inserted.

Throws: : The current instance is read-only or has a fixed size.

As described above. Use the System.Collections.IList.Add(System.Object) method to add another element to the current instance. The index into which that element is added is implementation-dependent.

public System.Void Clear()

Removes all items from the current instance.

Throws: : The current instance is read-only.

As described above. Implementations of this method can vary in how a call to this method affects the capacity of a list. Typically, the count is set to zero. The capacity can be set to zero, some default, or remain unchanged. Use this method to delete all values from the current instance.

public System.Boolean Contains(System.Object value)

Determines whether the current instance contains a specific value.

Parameter value: The System.Object to locate in the current instance.

Returns: true if the System.Object is found in the current instance; otherwise, false.

As described above. Use the System.Collections.IList.Contains(System.Object) method to determine if a particular System.Object is an element of the current instance.

public System.Int32 IndexOf(System.Object value)

Determines the index of a specific item in the current instance.

Parameter value: The System.Object to locate in the current instance.

Returns: The index of value if found in the current instance; otherwise, -1.

As described above. The default implementations of this method use System.Object.Equals(System.Object) to search for value in the current instance. Use System.Collections.IList.IndexOf(System.Object) to determine if a System.Object is contained in the current instance and, if it is contained, its index in the current instance.

public System.Void Insert(System.Int32 index, System.Object value)

Inserts an item to the current instance at the specified position.

Parameter index: A System.Int32 that specifies the zero-based index at which value is inserted.

Parameter value: The System.Object to insert into the current instance.

Throws: : index is not a valid index in the current instance (i.e. is greater than the number of elements in the current instance).

Throws: : The current instance is read-only or has a fixed size.

If index equals the number of items in the System.Collections.IList, then value is required to be appended to the end of the current instance. Use System.Collections.IList.Insert(System.Int32,System.Object) to place a new element into a specific position in the current instance.

public System.Void Remove(System.Object value)

Removes the first occurrence of a specified System.Object from the current instance.

Parameter value: The System.Object to remove from the current instance.

Throws: : The current instance is read-only or has a fixed size.

As described above. In addition, if value is null or is not found in the current instance, it is required that no exception be thrown and the current instance remain unchanged. The default implementations of this method use System.Object.Equals(System.Object) to search for value in the current instance. Use System.Collections.IList.Remove(System.Object) to delete a specified System.Object from the current instance.

public System.Void RemoveAt(System.Int32 index)

Removes the item at the specified index of the current instance.

Parameter index: A System.Int32 that specifies the zero-based index of the item to remove.

Throws: : index is not a valid index in current instance.

Throws: : The current instance is read-only or has a fixed size.

As described above. Use System.Collections.IList.RemoveAt(System.Int32) to delete a specified System.Object from the current instance.


Functions inherited from System.Collections.ICollection:

public System.Void CopyTo(System.Array array, System.Int32 index)

Copies the elements from the current instance to the specified System.Array, starting at the specified index in the array.

Parameter array: A one-dimensional, zero-based System.Array that is the destination of the elements copied from the current instance.

Parameter index: A System.Int32 that specifies the zero-based index in array at which copying begins.

Throws: : array is null.

Throws: : index < 0.

Throws: : array has more than one dimension. index is greater than or equal to array.Length. The sum of index and the System.Collections.ICollection.Count of the current instance is greater than array.Length.

Throws: : At least one element in the current instance is not assignment-compatible with the type of array.

As described above. Use this method to copy from a collection to a System.Array.


Functions inherited from System.Collections.IEnumerable:

public System.Collections.IEnumerator GetEnumerator()

Returns a System.Collections.IEnumerator that can be used for simple iteration over a collection.

Returns: A System.Collections.IEnumerator that can be used for simple iteration over a collection.

As described above. For a detailed description regarding the use of an enumerator, see System.Collections.IEnumerator.


Functions inherited from System.Collections.IEnumerable:

public System.Collections.IEnumerator GetEnumerator()

Returns a System.Collections.IEnumerator that can be used for simple iteration over a collection.

Returns: A System.Collections.IEnumerator that can be used for simple iteration over a collection.

As described above. For a detailed description regarding the use of an enumerator, see System.Collections.IEnumerator.


Functions inherited from System.Collections.ICollection:

public System.Void CopyTo(System.Array array, System.Int32 index)

Copies the elements from the current instance to the specified System.Array, starting at the specified index in the array.

Parameter array: A one-dimensional, zero-based System.Array that is the destination of the elements copied from the current instance.

Parameter index: A System.Int32 that specifies the zero-based index in array at which copying begins.

Throws: : array is null.

Throws: : index < 0.

Throws: : array has more than one dimension. index is greater than or equal to array.Length. The sum of index and the System.Collections.ICollection.Count of the current instance is greater than array.Length.

Throws: : At least one element in the current instance is not assignment-compatible with the type of array.

As described above. Use this method to copy from a collection to a System.Array.


Functions inherited from System.Collections.IEnumerable:

public System.Collections.IEnumerator GetEnumerator()

Returns a System.Collections.IEnumerator that can be used for simple iteration over a collection.

Returns: A System.Collections.IEnumerator that can be used for simple iteration over a collection.

As described above. For a detailed description regarding the use of an enumerator, see System.Collections.IEnumerator.


Functions inherited from System.Collections.IEnumerable:

public System.Collections.IEnumerator GetEnumerator()

Returns a System.Collections.IEnumerator that can be used for simple iteration over a collection.

Returns: A System.Collections.IEnumerator that can be used for simple iteration over a collection.

As described above. For a detailed description regarding the use of an enumerator, see System.Collections.IEnumerator.