Monday, September 29, 2008

Anonymous Types in C#

  1. Anonymous types in C# are a new concept which shipped with .net framework 3.5
  2. Anonymous types are nothing but it simply states that we dont have to define a type and that type is defined automatically by C# analysing the right hand side.
  3. Anonymous Types are very important in the LINQ word.
  4. Keyword var is used to declare an anonymous type.
  5. They are immutable and thus dont require any property getter or setter methods
  6. They must always be initialized so that the compiler can build the type defination and bind the anonymous type with that , and it is only possible only when we have any thing in the right hand side of an anonymous type thus anonymous types should always be initialized.

//1.Shows Simple anonymous varible declarations and iterating using for loop

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

//2.Show Simple anonymous variable declarations and iterating using foreach loop

 1: var fabonici = new int[]{1,1,2,3,5,8,13,21}; 
 2: foreach (var fibo in fabonici) 
 3: Console.WriteLine(fibo); 

//3.Linq query used as iterand in foreach statement.

 1: var fabonici = new int[]{1,1,2,3,5,8,13,21}; 
 2: foreach (var fibo in 
 3: from f in fabonici 
 4: where f%3 == 0 
 5: select f) 
 6: Console.WriteLine(fibo);

0 comments :

Post a Comment