Annonymous objects in C#

By | March 21, 2011

Do you know C# 3.5 and above allows you to create anonymous types using Automatic Property initializers ? Yes, you can declare a type directly while you code to hold abstract data. Lets see how you can do this :

var x = new { X = 20, Y = new MyObj(), Z = "New String" };

Well using this code, the CLR compiler will automatically generate a new concrete class with Readonly properties X , Y and Z having its datatypes int, MyObj and string respectively. Hence in your code you can use this object and later on if you want to declare an object with the same type you can do so using the Same structure.

C# compiler takes care of these code while compilation and produces concrete annonymous types in MSIL.

But while you do work with those objects you should remember that these objects has some restrictions.

1. You cannot declare a type without initializing it.
2. All the properties it produces will be readonly by default.
3. You cannot declare Methods for these types. C# compiler does not support that.
4. It directly inherits from Object, you cannot inherit the type from your custom interface.
5. You should use implicitely type var while holding the object, even though you have option to hold it in dynamic object introduced in C# 4.0

Read more about its internals from my post.
Thank you for reading.

One thought on “Annonymous objects in C#

  1. Pingback: Annonymous objects in C# | Daily .Net Tips | Learn Visual Studio

Comments are closed.