Reader Level:
ARTICLE

System.Array Class using C#

Posted by Puran Mehra Articles | C# Language January 18, 2010
In this article I will explain you about the System.Array Class using C#.
  • 0
  • 0
  • 44736
 

This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

Arrays are one of the fundamental data structures in programming languages, providing a storage area for sequential data values. System.Array is the base class for all arrays in the common language runtime. It has methods for creating, manipulating, searching, and sorting the arrays we have talked about so far. System.Array implements several interfaces, like ICloneable, IList, ICollection, and IEnumerable. It also has many properties and methods to aid you in determining information about your array.

The Length property of the array returns the total number of elements in all of the array's dimensions.

The Rank property returns the rank the number of dimensions of the array, which is useful in multidimensional arrays.

You can use the Clear function to reset a range of array elements to zero or to a null reference.

The GetLowerBound function returns the lower bound of the specified dimension in an array. GetLowerBound(0) returns the lower bound for the indexes of the first dimension of an array, and GetLowerBound(Rank-1) returns the lower bound for the indexes of the last dimension of an array.

The GetUpperBound function returns the upper bound of the specified dimension in an array. GetUpperBound(0) returns the upper bound for the indexes of the first dimension of an array, and GetUpperBound(Rank-1) returns the upper bound for the indexes of the last dimension of an array.

Using the Copy function, you can copy a range of elements from one array, starting at the specified source index, and paste them into another array, starting at the specified destination index:

// Copy the first 2 elements from mySourceArray to myDestinationArray Array.Copy( mySourceArray, mySourceArray.GetLowerBound(0), myDestinationArray, myDestinationArray.GetLowerBound(0), 2);

There are three ways to enumerate array elements:

  • Using the foreach loop structure
  • Looping with a for loop along the length of the array
  • Using the GetEnumerator function and implementing IEnumerator

Listing 20.10 illustrates these three enumeration methods

Listing 20.10: Looping Through Array Class Objects


//enumerating array elements

using
System;

class
Test
{
    public static void TestForEach(ref int[] myArray)
    {
        foreach (int x in myArray)
        {
            Console.WriteLine(x);
        }
    }

    public static void TestForWithLength(ref Object[] myArray)
    {
        for (int x = 0; x < myArray.Length; x++)
        {
            Console.WriteLine(myArray[x]);
        }
    }

    public static void TestForEnum(ref System.Array myArray)
    {
        System.Collections.IEnumerator myEnumerator = myArray.GetEnumerator();
        int i = 0;
        int cols = myArray.GetLength(myArray.Rank - 1);

        while (myEnumerator.MoveNext())
        {
            if (i < cols)
            {
                i++;
            }
            else
            {
                Console.WriteLine();
                i = 1;
            }
            Console.WriteLine(myEnumerator.Current);
        }
    }

    public static void Main()
    {
        // an int array and an Object array
        int[] myIntArray = new int[5] { 5, 4, 3, 2, 1 };
        TestForEach(ref myIntArray);

        // an Object array
        Object[] myObjArray = new Object[5] { 99, 98, 97, 96, 95 };
        TestForWithLength(ref myObjArray);

        // another object array
        Array myObjArray2 = Array.CreateInstance(Type.GetType("System.Object"), 5);
        for (int i = myObjArray2.GetLowerBound(0); i <=
        myObjArray2.GetUpperBound(0); i++)
            myObjArray2.SetValue(i * i, i);
        TestForEnum(ref myObjArray2);
    }
}


The .NET Framework provides IEnumerable and IEnumerator interfaces to implement and provide a collection like behavior to user-defined classes. These interfaces are implemented through inner classes. An inner or nested-type class is enclosed inside another class. Listing 20.11 is the pseudocode for the implementation of the enumerator.

Listing 20.11: Creating a custom Enumerator

using
System;
using
System.Collections;

class
ItemCollection : IEnumerable // COLLECTION
{
}


class
ItemIterator : IEnumerator // ITERATOR
{
    class ItemCollection
    {
        // class ItemCollection is an Inner Class or Nested Type in class ItemIterator
    }

    //IEnumerator and IEnumerable interfaces are defined in System.Collections
    //namespace as:
    public interface IEnumerable
    {
        IEnumerator GetEnumerator(); //returns an enumerator
    }

   public interface IEnumerator
    {
        bool MoveNext();
        //After an enumerator is created or after a Reset,
        //an enumerator is positioned before the first element
        //of the collection, and the first call to MoveNext
        //moves the enumerator over the first element of the
        //collection.
        // And next calls move the cursor one further till the end.
        object Current { get; }

        // Returns the current object from the collection.
        // You should throw an InvalidOperationException exception
        // if index pointing to wrong position.

        void Reset();
        // Resets enumerator to just before the first element of the collection.
        // Resets pointer to -1.
    }
}


In C# all array elements are initialized to their default values. For reference-type variables, the default value is null. You need to instantiate the reference element before you can access any member property; otherwise you receive an error. As shown in Listing 20.12, you can also use the Array.Initialize member function to initialize every element of a value-type array by calling the default constructor of the value type.

Listing 20.12: Array Initialization Example

// array initialization

using
System;

public
class DisplayPreferences
{
    string m_PropertyID;
    public DisplayPreferences()
    {
        m_PropertyID = null;
    }

    public string PropertyID
    {
        get { return m_PropertyID; }
        set { m_PropertyID = value; }
    }
}


public
class MySampleClass
{
    public static void Main()
    {
        DisplayPreferences[] oPrefs = new DisplayPreferences[10];
        // you have to initiliaze array items before use... otherwise
        /*

        The following error message is displayed if the array initialization below is not included.
        An unhandled exception of type 'System.NullReferenceException' occurred in displaypreferences.exe
        Additional information: Value null was found where an instance of an object was required.
        at MySampleClass.Main()        */


        for (int i = 0; i < oPrefs.Length; i++)
            oPrefs[i] = new DisplayPreferences();

        oPrefs[0].PropertyID = "ID007";

        // or if the array is of value-type, not necessary but...
        int[] intarr = new int[10];
        intarr.Initialize();
        intarr[0] = 7;
    }
}


Conclusion

Hope this article would have helped you in understanding the System.Array Class using C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

COMMENT USING

Trending up