Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of conditional expression cannot be determined (Func)

Tags:

When assigning a method to a Func-type, I get the compilation error Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.

This only happens with the ? : operator. The code:

public class Test {     public static string One(int value)     {         value += 1;         return value.ToString();     }     public static string Two(int value)     {         value += 2;         return value.ToString();     }     public void Testing(bool which)     {         // This works         Func<int, string> actionWorks;         if (which) actionWorks = One; else actionWorks = Two;          // Compilation error on the part "One : Two"         Func<int, string> action = which ? One : Two;     } } 

I found some information about co- and contravariance, but I don't see how that applies to the situation above. Why doesn't this work?

like image 412
doekman Avatar asked Jun 10 '11 15:06

doekman


1 Answers

You need to explicitly provide the signature of at least one method group. However, after doing it the compiler will allow you to declare action as an implicitly-typed local:

var action = which ? (Func<int, string>)One : Two; 

The reason this happens is that the return type of operator ?: is not deduced based on what you are trying to assign it to, but based on the types of the two expressions. If the types are the same or there is an implicit conversion between them, the compiler deduces the return type successfully; otherwise, it complains that there is no conversion.

like image 165
Jon Avatar answered Sep 23 '22 13:09

Jon