
.NET 3.0+C# Anonymous Types (2)
A new feature of C# 3.0 is the ability to create anonymous types. These interesting classes are defined for temporary use within class members. They allow the convenient encapsulation of read-only properties without the need to code a complete class.
GetHashCode Method
The GetHashCode method is overridden by anonymous types to provide compatibility with the Equals method. When the hash code is computed, the value of every property in the object is included in the calculation.
var cat1 = new { Name = "Mog", Age = 5 };
var cat2 = new { Name = "Tabby", Age = 5 };
var cat3 = new { Name = "Tabby", Age = 5 };
Console.WriteLine("cat1 / {0}", cat1.GetHashCode());
Console.WriteLine("cat2 / {0}", cat2.GetHashCode());
Console.WriteLine("cat3 / {0}", cat3.GetHashCode());
/* OUTPUT
cat1 / -1957230611
cat2 / -2011558908
cat3 / -2011558908
*/
GetType Method
The type of an anonymously typed object can be determined using the GetType method. If two or more objects contain the same property names and types in the same order, they are both created as the same type. This is shown in the following sample:
var cat1 = new { Name = "Mog", Sound = "Meow" };
var cat2 = new { Name = "Tabby", Sound = "Mew" };
new { Sound = "Mew", Name = "Tabby" };
Console.WriteLine("cat1 / {0}", cat1.GetType());
Console.WriteLine("cat2 / {0}", cat2.GetType());
Console.WriteLine("cat3 / {0}", cat3.GetType());
/* OUTPUT
cat1 / <>f__AnonymousType1`2[System.String,System.Int32]
cat2 / <>f__AnonymousType1`2[System.String,System.Int32]
cat3 / <>f__AnonymousType2`2[System.Int32,System.String]
*/
NB: Note the names of the anonymous types generated by the compiler. The names may vary slightly from that shown above.
ToString Method
The final method to be considered in this article is ToString. This method generates a string representation of the anonymously typed object. It combines all of the property names and values in a similar format to as they are declared. Using the feline examples for the last time, we can output several strings:
var cat1 = new { Name = "Mog", Age = 5 };
var cat2 = new { Name = "Tabby", Age = 5 };
var cat3 = new { Age = 5, Name = "Tabby" };
Console.WriteLine("cat1 / {0}", cat1.ToString());
Console.WriteLine("cat2 / {0}", cat2.ToString());
Console.WriteLine("cat3 / {0}", cat3.ToString());
/* OUTPUT
cat1 / { Name = Mog, Age = 5 }
cat2 / { Name = Tabby, Age = 5 }
cat3 / { Age = 5, Name = Tabby }
*/
Limitations
Anonymous types have similar limitations to implicitly typed variables. The key limitations are that anonymous types may only be used locally within class members. They may not be used in method parameters or return values, property declarations or as class-scope fields.
An anonymously typed object may be passed to the parameter of a method but must first be boxed into an object. This removes much of the usefulness of the type, so in these situations it is more appropriate to declare a real class instead.
4 June 2008