This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 3.0+

C# Anonymous Types

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.

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());


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());


cat1 / { Name = Mog, Age = 5 }
cat2 / { Name = Tabby, Age = 5 }
cat3 / { Age = 5, Name = Tabby }



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