Given two implementations of comparison methods:
private static int CompareByKey(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
{
return x.Key.CompareTo(y.Key);
}
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)