using Array Class and IEnumeration in C#

How to use

Copy the code in a text editor and save it as a .cs file and compile it using "csc <filename>"


This article illustrates the usage of Array class and IEnumerator. Array class Provides methods for creating, manipulating, searching and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

The Array class implements ICloneable, IList, ICollection and IEnumerable Interfaces. Hence we can use GetEnumerator method for creating Enumerators for our need. An Array class contains public static methods (like copy, createinstance,reverse, sort etc), public instance methods(like clone, CopyTo, GetLength, GetType etc.) and public instance properties (like Length, Rank etc). With an Array class we can create arrays for our needs using CreateInstance method.

The arrays so created possess more functionalities like sorting, reversing the elements and more. In the sample code I have used methods viz. Sort, CreateInstance, SetValue, GetLowerBound and GetUpperBound. We can use IEnumerator for the types which implements IEnumerable  and ICollection  interface. The IEnumerator posseses property called Current which gives the current position of Enumerator and methods like Reset, MoveNext which can control the position of the Enumerator.

In this code I haved used the concepts of Array and IEnumerator and used the methods to sort the name entered by the user by characters in a very simple way. The output will be the type of Enumerator, HashCode for the type and the sorted string.

Source Code:

using System;
using System.Collections;
namespace Collections
class Class1
public static int[] arr1 = new int[] {1,2,3,4};
public static string s = "";
public static string opt = "y";
static void Main(string[] args)
while ((opt == "y")|| (opt == "Y"))
Console.Write("Enter Your name :");
s = Console.ReadLine();
IEnumerator IEn = s.GetEnumerator();
Array a = Array.CreateInstance(
Console.WriteLine("Type :{0}",IEn.GetType());
Console.WriteLine("HashCode for the Type:{0}",(IEn.GetHashCode()));
for(int i = 0;i<s.Length; i++)
Console.Write("Your Name in the sorted form : ");
for(int i =
a.GetLowerBound(0);i<=a.GetUpperBound(0); i++)
Console.Write("Do You want to try again?(y/n): ");
opt = Console.ReadLine();

Recommended Free Ebook
Similar Articles