Saturday, February 6, 2010

Anonymous types - Examples

  • Simple
 var simple = "Simple Ann Type";
    string str= "Simple Ann Type";

Both the code are identical for MSIL
  • Array Initializer
var name = new string[] { "a","b","c" };
Console.WriteLine(name[0]);
  1. Composite Anonymous Types
    We can think of this use of anonymous types as defining an inline class without all of the typing. 

  •    var Person = new {FirstName="Bill", LastName="Clinton"};


    1.           Console.WriteLine(Person);//will produce - {FirstName="Bill", LastName="Clinton"}



    2.           Console.WriteLine(Person.FirstName);//will produce - Bill


      1.           Console.WriteLine(Person.LastName);//will produce - Clinton


        1.           //Person.FirstName = "s"; - ERROR : Error 1 Property or indexer AnonymousType#1.FirstName' cannot be assigned to -- it is read only

        2.   Console.ReadLine();

          A nice feature added to anonymous types is the overloaded ToString method.So when you call Person.FirstName actually MSIL interprets it as Person.FirstName.ToString()
          Output of the Composite Type

        3.           




          • In For Loops

        4.              var fibonacciSeries = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
                      Console.WriteLine("normal For Loop");
                      for (var i = 0; i < fibonacciSeries.Length; i++)
                          Console.WriteLine(fibonacciSeries[i]);
                      Console.WriteLine();

                      Console.WriteLine("For Each Loop");
                      foreach (var fibo in fibonacciSeries)
                          Console.WriteLine(fibo);

                      Console.WriteLine("Linq in action - prints all the even numbers in the list");
                      foreach (var fvar in from fib1 in fibonacciSeries where fib1 % 2 == 0 select fib1)
                          Console.WriteLine(fvar);

                      Console.ReadLine();




          • Return from Functions


        5.             var newPerson = getPerson();
                      Type typ = newPerson.GetType();
                      Console.WriteLine(typ.GetProperty("FirstName").GetValue(newPerson, null));//will produce - Bill       
                      Console.ReadLine();                                      
                  }

                  public static object getPerson()
                  {
                      var Person = new { FirstName = "Bill", LastName = "Clinton" };
                      return Person;
                  }


        6. Anonymous types can be returned from functions because the garbage collector (GC) cleans up any objects, but outside of the defining scope, the anonymous type is an
          instance of an object. As a practical matter, it is best to design solutions to use anonymous types within the defining scope.







        7. Post a Comment