Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

Scratching my head. What's wrong with the following statement?

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

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

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

I have already gone through this and this, but can't understand why compiler cannot determine the type of these 2 functions.

N.B. I know this can be fixed with explicit casting. I'm more interested in understanding the "why" part.

like image 805
dotNET Avatar asked Mar 02 '17 05:03

dotNET


1 Answers

I think the following explains why the compiler is having difficulties with this. Let's say we have:

string MyMethod() { return ""; }

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

// Not valid.
var method = MyMethod;

That is because there could be any number of delegates that could be used, for example:

delegate string MyDelegate();

With this we now have two options and it seems that it would be wrong for the compiler to assume one over the other:

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

// Valid.
MyDelegate myDel = MyMethod;

EDIT: For the sake of completion I'm adding a reference to this (it was mentioned by OP in the comments).

like image 80
Mario Z Avatar answered Oct 29 '22 02:10

Mario Z