Tuesday, July 27, 2010

Getting the value of a property through reflection.

For a project I am working on I needed to retrieve the value of a property.  Problem was I had a string that told me the name of the property.  Most .NET people out there would say just use reflection stupid.  Which is what I did but it was a learning experience for me. This is my first foray into reflection.  Here is the code.

public static object GetPropertyValue(object ObjectInstance, string WantedProperty)
        {
            var aviableProperties = ObjectInstance.GetType().GetProperties();
            var workingProperty = aviableProperties.FirstOrDefault(c => c.Name == WantedProperty);
            if (workingProperty != null)
            {
                return workingProperty.GetValue(ObjectInstance, null);
            }
            throw new ApplicationException(string.Format("The Property {0} was not found in the class.", WantedProperty));
        }

No comments: