Why can't the compiler determine the type of operands in this case?

Scratched his head. What happened to the following statement?

var EncFunc = (encrypt ? Encryption.Encrypt : Encryption.Decrypt); 

encrypt bool , both Encryption.Encrypt and Encryption.Decrypt functions are of the same type Func<string, string> , but it tells me that:

CS0173 The conditional expression type cannot be determined because there is no implicit conversion between the "method group" and the "method group"

I already went through this and this , but I can’t understand why the compiler cannot determine the type of these two functions.

NB I know that this can be fixed with explicit casting. I'm more interested in understanding why.

+5
source share
1 answer

I think the following explains why the compiler has difficulty with this. Say we have:

 string MyMethod() { return ""; } 

We cannot assign this method to var , in other words, we cannot use this:

 // Not valid. var method = MyMethod; 

This is because there can be any number of delegates that can be used, for example:

 delegate string MyDelegate(); 

Now we have two options, and it would seem to be wrong if the compiler allowed one over the other:

 // Valid. Func<string> myFunc = MyMethod; // Valid. MyDelegate myDel = MyMethod; 

EDIT: for the sake of completion, I am adding a link to this (in the comments it was mentioned by OP).

+6
source

Source: https://habr.com/ru/post/1264920/


All Articles