Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would it take to create a C# compilation error, when you use custom methods where Expression is expected?

What would it take to create a C# compilation error, when you use custom methods where Expression is expected?

Its true that Lambda expressions that contain invocations to custom methods are also, technically, well, expressions. But since the consumer of the expressions like LINQ to SQL, LINQ to JSON etc dont expect it, they throw runtime errors.

What can be done to let the compiler know what a framework like LINQ to SQL etc expects, and what aren't allowed.

like image 654
Zasz Avatar asked Dec 31 '25 07:12

Zasz


2 Answers

Nothing can be done, because of the following reasons:

  1. A lambda expression (!) that contains a method call is still an expression
  2. Not all method calls are illegal. Some methods are understood and correctly translated. So, even if you would find a way to only allow lambda expressions that don't call methods, you would disallow all method calls, even the valid ones.
like image 138
Daniel Hilgarth Avatar answered Jan 01 '26 22:01

Daniel Hilgarth


This is not possible. It would be similar to requiring that a variable of type string can not contain certain characters. The compiler is not able to check this, since the actual content of the variable is only known at runtime.

That said, the transformation from a lambda expression to an Expression instance is done by the compiler, so theoretically/technically, one could imagine a 'LINQ compiler service' that would integrate with the compiler, and provide information about the supported constructs at compile time.

It would obviously require a lot of work both in the compiler and in the LINQ providers (LINQ provider writers should in this scenario also implement this 'linq compiler interface' to integrate with this compiler service).

I wouldn't count on this to be available in the near future. Maybe the whole 'compiler as a service' (aka Roslyn) could enable this scenario?

like image 42
jeroenh Avatar answered Jan 01 '26 22:01

jeroenh