Power of Yield, Generics and Array in C#


When it is necessary to process a array in normal order, we can use statement foreach.

But if we want to process the array in reverse order: from last array's element to first (0) element, we have a problem. Sure, we can use loop for (in reverse order) or call method Array.Reverse() and reverse elements of original array. Now we can suggest a additional way to get reverse processing of array with help of generics and yield.

Sample: process (output to console) int and string array in "normal" and "reverse" orders:

static void SampleReverese()
    int[] intArray = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    string[] strArray = new string[] { "zero", "one", "two", "three", "four", "five" };           

We can note, methods DisplayArray() and ReverseArray() can receive array of any elements.

It is implemented with help of c# generics.

Method Display():
static void DisplayArray<T>(IEnumerable<T> displayedArray)
    foreach (T item in displayedArray)
        Console.Write("{0} ", item);

More interesting how to implement method Reverse() without creation of new array or changing original array.
We use statement yield:

static IEnumerable<T> Reverse<T>(T[] originalArray)
   for (int i = originalArray.Length - 1; i>=0; i--)
       yield return originalArray[i];



Similar Articles