Reputation: 6813
I have a problem where in some cases (appears to be where property type is bool) a lambda expression used to refer to a property. I use this to get its name; the problem is sometime the expression is getting modified to have an additional Convert() function.
e.g.
GetPropertyName<TSource>(Expression<Func<TSource, object>> propertyLambda) {...}
var str = GetPropertyName<MyObject>(o=>o.MyBooleanProperty);
What's happening it that the propertyLambda looks like Convert(o.MyBooleanProperty)
and not o.MyBooleanProperty
that i'd expect.
Upvotes: 4
Views: 344
Reputation: 244767
The Convert
is added, because o.MyBooleanProperty
is a bool
, but the result has to be an object. If you made your method generic both in the source object type and the result type, then there would be no Convert
:
GetPropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> propertyLambda)
Unfortunately this means you have to specify TResult
explicitly:
GetPropertyName<MyObject, bool>(o => o.MyBooleanProperty)
If you don't want to do that, you would have to find some way to infer MyObject
, or avoid needing it.
For example, if the current object is MyObject
(and you're in an instance method), you could change your code to take Func<TResult>
:
GetPropertyName(() => this.MyBooleanProperty)
Or you could include another parameter of type TSource
that will help you infer the type:
GetPropertyName(myObject, o => o.MyBooleanProperty)
Upvotes: 3