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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With