Sam
Sam

Reputation: 4339

Lambda not a property type when passing property

I have the following class:

public class Errors<T> : Errors
{
    public void Add(Expression<Func<T>> property, string message)
    {
        base.Add(((MemberExpression)property.Body).Member.Name, message);
    }
}

Which I then try and invoke like this:

Errors<User> e = new Errors<User>();
e.Add(x => x.Name, "Name must be entered.");

When I attempt to compile, I get the following error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

Where is my definition wrong? The error occurs on the e.Add method call, not on the overload.

Upvotes: 0

Views: 49

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

You've specified Func<T> in your overload, which should take no argument and return T (in this case, User). You're passing a lambda which looks more like Func<T, object> - it accepts a T parameter and returns something.

I imagine your Errors base class has a function like this:

public class Errors{    
    public void Add(string propertyName, string message) {
        // implementation here
    }    
}

Which is what the error is talking about. It's trying to match your lambda to the parameters of that overload, because it doesn't match the Func<T> you specified in your generic class's overload.

So, I think your overload should be:

public void Add(Expression<Func<T, object>> property, string message)

Upvotes: 2

Related Questions