Array class and IEnumerator in C#

 

This article illustrates the usage of Array class and IEnumerator in C#.

Array class Provides methods for creating,manipulating, searching and sorting arrays, thereby serving as the baseclass for all arrays in the common language runtime.

The Array class implements ICloneable, IList, ICollection andIEnumerable Interfaces. Hence we can use GetEnumerator method forcreating Enumerators for our need.

An Array class contains public static methods(like copy, createinstance,reverse, sort etc), public instancemethods(like clone,CopyTo, GetLength, GetType etc.) and public instanceproperties (like Length, Rank etc)With an Array class we can create arrays for our needs usingCreateInstance method. The arrays so created possess morefunctionalities like sorting, reversing the elements and more. In thesample code I have used methods viz. Sort, CreateInstance, SetValue,GetLowerBound and GetUpperBound.

We can use IEnumerator for the types whichimplements IEnumerable and ICollection interface. The IEnumeratorposseses property called Current which gives the current position ofEnumerator and methods like Reset, MoveNext which can control theposition of the Enumerator.

In this code I haved used the concepts ofArray and IEnumerator and used the methods to sort the name entered bythe user by characters in a very simple way.

The output will be the type of Enumerator, HashCode for the type and the sorted string.

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(typeof(char),s.Length);
Console.WriteLine("Type :{0}",IEn.GetType());
Console.WriteLine("HashCode for the Type:{0}",(IEn.GetHashCode()));
IEn.Reset();
IEn.MoveNext();
for(int i = 0; i < s.Length ; i++)
{
a.SetValue(IEn.Current,i);
IEn.MoveNext();
}
Array.Sort(a);
Console.Write("Your Name in the sorted form : ");
for(int i = a.GetLowerBound(0);i<=a.GetUpperBound(0); i++)
{
Console.Write(a.GetValue(i));
}
Console.WriteLine("");
Console.Write("Do You want to try again?(y/n): ");
opt = Console.ReadLine();
}
}
}
}

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!