Anonymous Types


C# 2.0 invented anonymous methods, methods where you don’t specify a name and only define the method implementation with a parameter. The compiler still defines a method with a name. Anonymous types are new with C# 3.0. Here, you define a type without specifying a name.

The syntax to define an anonymous type is similar to an array initializer. There’s just a new before the curly brackets. Within the curly brackets properties with their values are defined. The anonymous type here has the properties Firstname and Lastname. After the anonymous type is created, you can use the properties similar to a normal type, as shown in the Console.WriteLine() method.

  var p1 = new { Firstname="Mario", Lastname="Andretti" }; Console.WriteLine(p1.Firstname + " " + p1.Lastname); 

Anonymous types become very handy with LINQ expressions and were already used in an example. Let’s have a look at the example that was done previously. The query expression shown sorts the Racer collection by dividing the Starts property through the Wins property. Then the select expression uses the new syntax to create an anonymous type. The type is created by assigning the combined Firstname and Lastname properties of the Racer to the property Name of the new type. The new type also has a property WinRelation that is calculated from the Starts and Wins properties from the Racer class.

 var winRelation = from r in Formula1.GetRacers()                   orderby ((float)r.Starts / r.Wins)                   select new { Name=r.Firstname + " " + r.Lastname,                                WinRelation = (float)r.Starts / r.Wins};

The anonymous type is then used in the foreach loop. Of course, as the type of the elements is anonymous, the type cannot be written to the declaration of the foreach statement. That’s a good place for the use of the var keyword for type inference.

 foreach (var r in winRelation) {    Console.WriteLine("{0}, {1:#.##}", r.Name, r.WinRelation); }




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net