- Simple
var simple = "Simple Ann Type";
string str= "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]);
- Composite Anonymous Types
We can think of this use of anonymous types as defining an inline class without all of the typing.
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
- In For Loops
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
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;
}
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.
Comments