Error assigning delegate ?: Syntax

I 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 one 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 an error message:

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

I can use the usual if ... else to complete this task, and it works fine. But I do not understand why I cannot use the more compact version, and I do not understand the error message. Does anyone know the meaning of this error?

+4
source share
2 answers

The types of the conditional operator are permitted before the assignment, so the compiler cannot use the type in the assignment to resolve the conditional operator.

Just add one of the operands to CharComparer so that the compiler knows what to use this type:

 CharComparer isEqual = ignoreCase ? (CharComparer)CharCompareIgnoreCase : CharCompare; 
+7
source

Try the following:

 CharComparer isEqual = (ignoreCase) ? new CharComparer(CharCompareIgnoreCase) : new CharComparer(CharCompare); 
+2
source

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


All Articles