The Lambda property of the expression gets an extra Convert (p => p.Property)

I have a problem when in some cases (it seems that the type of the property is bool) the lambda expression is used to denote the property. I use this to get his name; the problem is that once an expression gets modified to have the extra Convert () function.

eg.

GetPropertyName<TSource>(Expression<Func<TSource, object>> propertyLambda) {...} var str = GetPropertyName<MyObject>(o=>o.MyBooleanProperty); 

What happens is that the Convert(o.MyBooleanProperty) property looks like Convert(o.MyBooleanProperty) , and not the o.MyBooleanProperty that I would expect.

+4
source share
1 answer

Convert added because o.MyBooleanProperty is a bool , but the result should be an object. If you created your general method in both the original object type and the result type, then there would be no Convert :

 GetPropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> propertyLambda) 

Unfortunately, this means that you must explicitly specify TResult :

 GetPropertyName<MyObject, bool>(o => o.MyBooleanProperty) 

If you do not want to do this, you will need to find a way to draw the conclusion of MyObject or to avoid the need.

For example, if the current object is MyObject (and you are in the instance method), you can change your code to accept Func<TResult> :

 GetPropertyName(() => this.MyBooleanProperty) 

Or you can include another parameter of type TSource , which will help you deduce the type:

 GetPropertyName(myObject, o => o.MyBooleanProperty) 
+3
source

All Articles