tags:

views:

1383

answers:

3

Hi guys,

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.

+4  A: 

You can do this:

typeof(MyObject).GetProperty("MyProperty")

However, since C# doesn't have a "symbol" type, there's nothing that will help you avoid using string. Why do you call this type-unsafe, by the way?

Vojislav Stojkovic
Because it's not evaluated at compile time? If I changed my property name or typo'd the string I wouldn't know until the code ran.
tenpn
A: 

Reflection is used for runtime type evaluation. So your string constants cannot be verified at compile time.

Darin Dimitrov
+10  A: 

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();
        }
    }
}
Marc Gravell
Nice solution but unfortunately I'm not using .NET3.5. Still, tick!
tenpn
In 2.0, Vojislav Stojkovic's answer is the closest you can get.
Marc Gravell