Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Assigning Delegate Using ? : Syntax

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?

like image 896
Jonathan Wood Avatar asked Jan 20 '23 09:01

Jonathan Wood


1 Answers

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;
like image 172
Guffa Avatar answered Jan 29 '23 07:01

Guffa