Getting an Anonymous Type Value

The following is a extension method that will get the value from an Anonymous Type:

public static T GetAnonymousValue<T>(this object o, string propertyName)
{
    System.Reflection.PropertyInfo pi = o.GetType().GetProperty(propertyName);
    T retVal = default(T);
    if (pi != null)
    {
        retVal = (T)pi.GetValue(o, null);
    }
 
    return retVal;
}

Take into account that it will throw a Specified cast is not valid if it cannot cast to the passed type.

Comments are closed.