ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetPropertyValue

Gets the value of a property in a object through relection

Source

public static T GetPropertyValue<T>(this object source, string property)
{
    if (source == null)
        throw new ArgumentNullException("source");

    var sourceType = source.GetType();
    var sourceProperties = sourceType.GetProperties();

    var propertyValue = (from s in sourceProperties
                         where s.Name.Equals(property)
                         select s.GetValue(source, null)).FirstOrDefault();

    return propertyValue != null ? (T)propertyValue : default(T);
}

Example

user.GetPropertyValue<string>("Name");

Author: Sanction10

Submitted on: 2 sep. 2010

Language: C#

Type: System.Type

Views: 9348