I've created a delegate and two matching methods.
private delegate bool CharComparer(char a, char b);
// Case-sensitive char comparer
private static bool CharCompare(char a, char b)
{
return (a == b);
}
// Case-insensitive char comparer
private static bool CharCompareIgnoreCase(char a, char b)
{
return (Char.ToLower(a) == Char.ToLower(b));
}
When I try to assign either of these methods to a delegate using the following syntax (note that this code is in a static method of the same class):
CharComparer isEqual = (ignoreCase) ? CharCompareIgnoreCase : CharCompare;
I get the error:
Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'
I can use a regular if ... else
statement to do this assignment and it works just fine. But I don't understand why I can't use the more compact version and I don't understand the error message. Does anyone know the meaning of this error?
The types in the conditional operator is resolved before the assignment, so the compiler can't use the type in the assignment to resolve the conditional operator.
Just cast one of the operands to CharComparer
so that the compiler know to use that type:
CharComparer isEqual = ignoreCase ? (CharComparer)CharCompareIgnoreCase : CharCompare;
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