1

Some trouble with UnaryExpressions.

This works this way:

Expression<Func<List<string>, object>> k = l => l.Count;
//got member in this case like this
var member = ((k.Body as UnaryExpression).Operand as MemberExpression).Member;

In the above case the k.Body.NodeType was ExpressionType.Convert. But it's a little tricky with ExpressionType.ArrayLength. How would I get the PropertyInfo member similarly in the below case?:

Expression<Func<string[], int>> k = l => l.Length;
var member = ??

In the second case k.Body is something like ArrayLength(l).

I can do it with a hack like this:

var member = (k.Body as UnaryExpression).Operand.Type.GetProperty("Length");

but this doesn't feel like a straight forward expression approach. It's more a plain old reflection call with dirty string "Length" passed. Is there a better way?

nawfal
  • 70,104
  • 56
  • 326
  • 368

1 Answers1

4

It's an ArrayLength node, which you can create with the Expression.ArrayLength method.

It's just a UnaryExpression with an Operand which is the array expression, and a NodeType of ArrayLength. It's not entirely clear to me what you wanted to know about it, but hopefully the call to Expression.ArrayLength is what you were after.

EDIT: Although there is an Array.Length property, that's not what's used normally. For example:

int[] x = new int[10];
Array y = x;

int a = x.Length;
int b = y.Length;

... then evaluating x.Length uses the ldlen IL instruction whereas evaluating y.Length uses a call to the property.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I want to know how to get the `PropertyInfo` of `Length` property from `l.Length` part of the expression. How do I get that from `Expression.ArrayLength` method? – nawfal Oct 12 '13 at 16:12
  • @nawfal: It's not a property, so there *is* no such `PropertyInfo`. – Jon Skeet Oct 12 '13 at 16:13
  • I guess it is a property. For instance I can get the `PropertyInfo` of a typical `int[].Length` like `typeof(int[]).GetProperty("Length")`. – nawfal Oct 12 '13 at 16:15
  • @nawfal: Sorry, to clarify - that's the `Array.Property` length, but if you use `int[] x = ...; int y = x.Length;` then that *doesn't* use the property. – Jon Skeet Oct 12 '13 at 16:17
  • Then what does it use ultimately? If anything shouldn't it have a `MemberInfo` associated with it? – nawfal Oct 12 '13 at 16:18
  • 1
    @nawfal: No, it's special basically. See my edit for more details. – Jon Skeet Oct 12 '13 at 16:19