How can I get a value of a property from an anonymous type (C#)

Last day I have faced a problem when working with  "Anonymous Type". In development procedure I have got  result from a service which return object made of anonymous type. The problem arise when I need to access property of anonymous type. After made some r&d I have got the solution. Now share with you ....

Solution 1: (use reflection to retrieve the values of the following anonymous type)

var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// clientname  return the result Ahsan

More generic solution:

public static T GetValueFromAnonymousType( object dataitem, string itemkey ) 
    System.Type type = dataitem.GetType();
    T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
    return itemvalue;

 var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
 string clientname = GetValueFromAnonymousType(obj, "ClientName");

Solution 2:

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
string clientname = TypeUtils.GetValueFromAnonymousType(obj, "ClientName");

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
Type t = obj.GetType();

//Then from that you look up a property:
PropertyInfo p = t.GetProperty("ClientName");

//Then from that you can get a value:
object v = p.GetValue(obj, null);

//This answer is long overdue for an update for C# 4:
dynamic d = obj;
object v = d.ClientName;

Hope that it may helpful for others.


Zahed said…
thanks guy..your solution make my life easy :)

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."