Pages

Tuesday, October 9, 2012

In this post I am going to discuss about returning the anonymous type and how to handle in code. Following is list of fact about anonymous type.

Quick facts about Anonymous type

Anonymous types are reference type derived form system.objects.

Properties of the Anonymous type is read only.

If two Anonymous type has same properties and same order than compiler treats its as same type. But if both are in one assembly.

Anonymous type has method scope. If you want to return Anonymous type form the method than you have to convert it in object type. But is not good practice.

You can read more on blog about this: Anonymous types
As in about facts you cannot return anonymous type from the method , if you want to return you need to cast it in object.
Now in following post I am going to do same return the anonymous type as object and going to show three different way to handle it.

Way 1: Handle using Dynamic type

Way 2: Handle by creating same anonymous type

Way 3: Handle using Reflection

To Understand each way I created following method which returns anonymous type

As you see in above example first line of code calling method which is returning anonymous type as object and assign the return value to dynamic type. Second line of code just printing the property value of anonymous type.
Note : No intelligence support as we are using dynamic type. And need to remember the property name and type also.

This way making use of reflection feature of .net. First line of code call the method and assign return value to refobj. Second line of code get the Type of the object and than following line of code get the property of anonymous type and print value of it.Check out full Source code of to test all technique we discuss