How to get the PropertyInfo of a specific property?


Answers

There is a .NET 3.5 way with lambdas/Expression that doesn't use strings...

using System;
using System.Linq.Expressions;
using System.Reflection;

class Foo
{
    public string Bar { get; set; }
}
static class Program
{
    static void Main()
    {
        PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);
    }
}
public static class PropertyHelper<T>
{
    public static PropertyInfo GetProperty<TValue>(
        Expression<Func<T, TValue>> selector)
    {
        Expression body = selector;
        if (body is LambdaExpression)
        {
            body = ((LambdaExpression)body).Body;
        }
        switch (body.NodeType)
        {
            case ExpressionType.MemberAccess:
                return (PropertyInfo)((MemberExpression)body).Member;
            default:
                throw new InvalidOperationException();
        }
    }
}
Question

I want to get the PropertyInfo for a specific property. I could use:

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
    if ( p.Name == "MyProperty") { return p }
}

But there must be a way to do something similar to

typeof(MyProperty) as PropertyInfo

Is there? Or am I stuck doing a type-unsafe string comparison?

Cheers.




C# Reflection - Get PropertyInfo without a string

See here. The idea is to use Expression Trees.

public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

And then use it like:

var name = GetPropertyName<MyClass, string>(c => c.FirstName);

A bit cleaner solution would be if one would not required to specify so much generic parameters. And it is possible via moving MyClass generic param to util class:

public static class TypeMember<T>
{
    public static string GetPropertyName<TReturn>(Expression<Func<T, TReturn>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}

Then usage will be cleaner:

var name = TypeMember<MyClass>.GetPropertyName(c => c.FirstName);



You could do that

var property = ExpressionExtensions.GetProperty<MyClass>(o => o.FirstName);

With this helper :

public static PropertyInfo GetProperty<T>(Expression<Func<T, Object>> expression)
{
     MemberExpression body = (MemberExpression)expression.Body;
     return typeof(T).GetProperty(body.Member.Name);
}



C# get member's type ignoring it's value?

The only way to get it's type without an instance is using the declaring type:

var type = typeof(Program)
     .GetProperty("a", BindingFlags.Static | BindingFlags.Public)
     .PropertyType;



No, what you have is about as clean as it gets.




Tags