C# 3.0: Anonymous Type

Published 21 July 07 09:45 AM | adrian

So earlier this week I've blogged about the auto-implemented property. A thing it uses is anonymous type. WTH is it?

C# 2.0 seen anonymous method as a way of defining a method (for delegates) without requiring it to have a method name (hence, it'll only be called from one point, the delegate). Anonymous type does the same thing. You can create a type (a.k.a. class) without requiring it to be a full blown type declaration (has a name, namespace, methods, etc.).

To use (not declare) an anonymous type, you can just use this:

var p1 = new {Name = "A", Price = 3};

There goes a new type. You can then access it's properties just like a common type:

Console.WriteLine(p1.Name);
Console.WriteLine(p1.Price);

Behind the scenes, when the above code is compiled, the compiler will autogenerate a class (that means you can access it via Reflector or System.Reflection, for instance) with private fields and public getter/setter property, plus a constructor assigning given values (in this case "A" and 3) to the appropriate fields.

Next question is, when do we use this anonymous type and auto-implemented property? That's next.

Share this post: | | | |
Filed under:

Comments

No Comments