michael
michael

Reputation: 15302

Ensure that a lambda expression points to an actual property of a class?

Is there any way to ensure that I can only pass in an expression that points to property on the a class?

public class Foo
{
    public string Bar { get; set; }

    public void DoSomething()
    {
        HelperClass.HelperFunc(() => Bar);
    }
}

public static class HelperClass
{
    public static void HelperFunc(Expression<Func<string>> expression)
    {
        // Ensure that the expression points to a property
        // that is a member of the class Foo (or throw exception)
    }
}

Also, if need be, I can change the signature to pass the actual class in as well...

Upvotes: 2

Views: 120

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

Here is extension method, which converts lambda to property. If lambda does not points to property, exception is thrown

public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)
{
    MemberExpression body = expression.Body as MemberExpression;
    if (body != null)
    {
        PropertyInfo member = body.Member as PropertyInfo;
        if (member != null)
        {
            return member;
        }
    }
    throw new ArgumentException("Property not found");
}

Upvotes: 2

Related Questions