Annonymous objects in C#

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Annonymous objects in C#”

Comments are closed.