Friday, April 27, 2012

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;
}

Example:
 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.
Thanks

1 comment:

Zahed said...

thanks guy..your solution make my life easy :)

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...