From: Jehu Galeahsa on
Hello:

I am trying to write a little helper class that allows a syntax like
this:

string name = Grab<int[]>.Property(values => values.Length).Name;

The idea here is that I want to grab a property, method, etc. from a
type quickly. When I am writing a lot of reflection, it would be
really helpful to use a class like this to avoid things like hard-
coding property names. I also want to know that should I refactor, I
don't have to change string literals.

The problem seems that MS has a bunch of optimizations I wasn't
expecting. So, the example above bombs horribly. You see, the sa =>
sa.Length expression is not a MemberExpression, it is a
UnaryExpression. Instead of Length being a property, a unary call
named ArrayLength is being called on the array. This is probably great
for performance, but horrible for what I am trying to do. I have
noticed a few other, similar oddities.

Is there a way to force C# to reference properties? I could handle
every special case, but that would require me to write special cases,
which I hate. I think such a class would be extremely useful, but it
doesn't seem to work in some situations, like this one. Is there any
guarantee that more special cases won't appear in later versions? Is
there a place to see all of the special cases?

Thanks,
Travis Parks
From: Peter Duniho on
Jehu Galeahsa wrote:
> [...]
> Is there a way to force C# to reference properties? I could handle
> every special case, but that would require me to write special cases,
> which I hate. I think such a class would be extremely useful, but it
> doesn't seem to work in some situations, like this one. Is there any
> guarantee that more special cases won't appear in later versions? Is
> there a place to see all of the special cases?

Sounds like you're running into inlining of the property getter.

There's a hack that suppresses inlining; I don't recall the specifics
off the top of my head, but I'm sure you can find it with Google using
keywords like "C# suppress inlining".

For what it's worth, these are the kinds of headaches you sign up for
when you build an entire system around reflection. :)

Pete