0

I've resolved numerous fights with C# not being able to resolve two lambdas in a conditional expression used to initialize a var. However today I faced what was seemingly a pretty easy and straight-forward pair of lambdas which I could not fight the compiler into accepting as the two results on a conditional expression. The compiler had no problem with them separately using an if-then-else construct instead.

Thus I decided to reduce the code down to as bare minimum as possible to show the problem, and discovered I could reduce it to pretty rock bottom and still get the error.

The compiler is issuing the usual error:

CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

The following code is three examples of pretty rock-bottom code that still generates the error. The first line (test1) being what should be reasonably usable enough. The other lines being efforts to clarify through precedence and explicit typing.

Considering I have successfully used conditionals to select between two somewhat more complex (although not very complex) lambdas before, I was surprised to discover these extremely simple examples don't work.

Anybody know what's going on here?

In my case it's a C# UWP project set to build using C# 7.3. Visual Studio is not reporting any pending updates.

Func<int, int> test1 = true ? (a) => 0 : (a) => 0;

Func<int, int> test2 = true ? ((int a) => (int)0) : ((int a) => (int)0);

Func<int, int> test3 = true ? ((int a) => { return (int)0; }) : ((int a) => { return (int)0; });
H H
  • 263,252
  • 30
  • 330
  • 514
kburgoyne
  • 181
  • 1
  • 2
  • Could you give an example which *does* work? I'd be somewhat surprised to see conditional expressions using lambda expressions for second and third operands work in *any* cases. – Jon Skeet Jun 09 '19 at 19:22
  • 2
    Note that if you cast either lambda expression to a concrete delegate type in each case, I'd expect that to then work fine. The problem is that lambda expressions themselves don't have a type. – Jon Skeet Jun 09 '19 at 19:27
  • Thanks @Servy. The search system didn't find the question you referenced when I started mine. – kburgoyne Jun 10 '19 at 23:28
  • Now I understand what's going on. I'm thinking our prior tendencies had been for one side of the conditional to be a method reference and the other side a lambda (typically a default "do nothing"). So the compiler must have been taking its hint from the method. – kburgoyne Jun 10 '19 at 23:48
  • I wouldn't expect a method group to work either - again, it doesn't have a type. This is where a concrete example of what does work would be really helpful. – Jon Skeet Jun 11 '19 at 05:21

0 Answers0