开发者

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

开发者 https://www.devze.com 2023-04-07 20:15 出处:网络
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, technica开发者_如何学Golly, 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:

  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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号