Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in C#: "an expression tree may not contain a base access" - why not?

I was calling a method that accepts Expression<Func<bool>>.

As part of the expression I was passing:

this.Bottom == base.lineView.Top 

The compiler gave me an error that

an expression tree may not contain a base access

So I simply changed it to

this.Bottom == this.lineView.Top 

because the member was protected anyway and now it works.

But this error really got me: why the heck would this base be a problem? Especially if using this instead will work but syntactically be the same result (same variable gets accessed)?

like image 826
Krumelur Avatar asked Mar 08 '14 19:03

Krumelur


People also ask

What are the 3 types of programming errors?

When developing programs there are three types of error that can occur: syntax errors. logic errors. runtime errors.

How many types of error are there in C?

Errors are mainly 5 types that are Syntax errors, Run-time errors, Linker errors, Logical errors, and Logical errors.

What is program error?

Program Error means there is incongruence between the behavior of the Software and the documented functionality and operation of the Software or any other problem or irregularity which affects the material functionality of the Software.


1 Answers

Looking at the System.Linq.Expressions.Expression documentation, I don't think there's an expression type which represents "base member access". Don't forget that even though in your case it meant the same as just this, in other cases it wouldn't:

class Test {     void Foo()     {         Expression<Func<string>> baseString = () => base.ToString();     }      public override string ToString()     {         return "overridden value";     } } 

Here that would represent a non-virtual call to Object.ToString() (for this). I can't see how that would be represented in an expression tree, hence the error.

Now that leads on to the obvious question of why there isn't a representation of non-virtual base member invocation in expression trees - I'm afraid I can't answer that part... although I can see that if you could build that expression programmatically, that would allow you to bypass normal polymorphism from the outside instead of only from inside the class itself (which is the normal case). That may be the reason. (Admittedly there are other ways of calling methods non-virtually, but that's a different matter, and I dare say there are situations where expression trees are "trusted" but other code isn't.)

like image 199
Jon Skeet Avatar answered Sep 19 '22 19:09

Jon Skeet