I hope you are aware of some in-built design patterns in C#. 

 Here is some code snippets.

      ArrayList arrayList = new ArrayList();

      int []array = {1,2,3,5};

      foreach(int i in array)

      {

            Console.WriteLine(i);

            arrayList.Add(i);   // Fill ArrayList

      }

      foreach(int i in arrayList)

      {

            Console.WriteLine(i);

      }

 When I opened the MSIL code (generated by C# compiler) got interesting results.

Compiler is replacing ArrayList foreach statement using  IEnumerable as given below.

     IL004f:  br.s       IL0065

    IL0051:  ldloc.s    CS$00000006$00000002

    IL0053:  callvirt   instance object [mscorlib]System.Collections.IEnumerator::getCurrent()

    IL0058:  unbox      [mscorlib]System.Int32

    IL005d:  ldind.i4

    IL005e:  stloc.3

    IL005f:  ldloc.3

    IL0060:  call       void [mscorlib]System.Console::WriteLine(int32)

    IL0065:  ldloc.s    CS$00000006$00000002

    IL0067:  callvirt   instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()

    IL006c:  brtrue.s   IL0051

 But C# array is handled using simple loop (br.s). Hence consider (better performance) simple array if you are using basic types (integer, string etc) , Since C# is implementing Iterator pattern using IEnumberable interface.

Leave a Reply

*