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.
Nothing can be done, because of the following reasons:
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With