How do I get the value of MemberInfo?

Although I generally agree with Marc’s point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don’t care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful’s answer to this question):

    public static object GetValue(this MemberInfo memberInfo, object forObject)
    {
        switch (memberInfo.MemberType)
        {
            case MemberTypes.Field:
                return ((FieldInfo)memberInfo).GetValue(forObject);
            case MemberTypes.Property:
                return ((PropertyInfo)memberInfo).GetValue(forObject);
            default:
                throw new NotImplementedException();
        }
    } 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)