Conditional operator and comparison delegate

Given two implementations of comparison methods:

// compares by Key...
private static int CompareByKey(KeyValuePair<int, string> x, KeyValuePair<int, string> y)

{
    return x.Key.CompareTo(y.Key);
}

// compares by Value...
private static int CompareByValue(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
{
    return x.Value.CompareTo(y.Value);
}

Why not compile the following block of conditional operator code:

Comparison<KeyValuePair<int, string>> sortMethod;
sortMethod = isSortByActualValue ? CompareByKey : CompareByValue;

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

However, the equivalent code block using if-else has no problem:

Comparison<KeyValuePair<int, string>> sortMethod;
if (isSortByActualValue)
    sortMethod = CompareByKey;
else
    sortMethod = CompareByValue;

(all is good in both appointments above)

So is the conditional operator if I passed the comparison delegate:

Comparison<KeyValuePair<int, string>> sortMethod;
sortMethod = isSortByActualValue ? (Comparison<KeyValuePair<int, string>>) CompareByKey : CompareByValue;

(all is well in the task above when it is cast, although casting was only on the true part)

+5
source share
2 answers

Th , . , . "group", , .

, if .

. ?: , , ( ). , , .

: , , . , .

, :

object = someBool ? "" : New List<Integer>();

. , , :

object = someBool ? (object) "" : New List<Integer>();
+7

CompareByKey, .Net, . , , CompareByKey, , ( , ). , , , . Comparison<KeyValuePair<int, string>> Func<KeyValuePair<int, string>, int>.

? (new Comparison<KeyValuePair<int, string>>(CompareByKey)), . if .

, ? , , ( , #). , - , . .

: , , ( ).

+3

All Articles