Why are some properties of the UnaryExpression object and other MemberExpression?

Fulfilling the answer to mine, select the model property using the lambda name rather than the string property name , wanting to add the properties to the collection as follows:

var props = new ExportPropertyInfoCollection<JobCard>(); props.Include(model => model.BusinessInstallNumber).Title("Install No").Width(64).KeepZeroPadding(true); props.Include(model => model.DeviceName).Title("Device").Width(70); props.Include(model => model.DateRequested).Title("Request Date").Format("{0:dd/MM/yyyy}").Width(83); 

I wrote the following code in the Include method:

 public class PropertyCollection<T> { public void Include(Expression<Func<T, object>> expression) { var memberExpression = expression.Body as MemberExpression; if (memberExpression != null) { var pes = new ExportPropertyInfoBuilder {Property = new ExportPropertyInfo {Property = memberExpression.Member as PropertyInfo}}; Properties.Add(pes.Property.Property.Name, pes.Property); return pes; } 

However, when I ran the code, I found that some of the lambdas gave MemberExpression values ​​as expected, but others gave UnaryExpression values. I had to change the first line of code to the following before I could add all my properties using lambdas:

 var memberExpression = expression.Body as MemberExpression ?? ((UnaryExpression) expression.Body).Operand as MemberExpression; 

All properties are "simple", i.e. string, DateTime, int, bool, etc. in the POCO business object. They are decorated with several changing attributes of DataAnnotations .

What makes some of the lambdas in my example get MemberExpression values ​​and other UnaryExpression values? In my example, the first UnaryExpression is on the third line, the DateTime property, but the boolean properties also lead to UnaryExpressionions .

+63
linq linq-expressions
Aug 25 '10 at 15:57
source share
1 answer

I think I know what the problem is. Your expression returns the type object .

If you change this to Expression<Func<T, R>> , the return type must be correctly inferred, and UnaryExpression (which I assume is some kind of boxing operation) should not occur.

Update:

The signature for Include must be:

 public void Include<T, R>(Expression<Func<T, R>> expression) 
+51
Aug 26 '10 at 8:17
source share



All Articles