The conditional operator ?:
as used in the form condition ? x : y
has a few rules about type conversion.
If both types are the same no problem or if one side supports an implicit conversion to the other but not vice-versa then that is used.
If neither of these cases were true you had to specify the desired type such as by casting the second argument.
C# 9.0 relaxes this rule by considering the "target type" - in the case of a variable assignment the declared type (so var
won't work) and in the case of a return statement the return type of the method or function.
Code
C#
// Inferring from declared variable type
IList<int> list = capacity > 0 ? new List<int>(capacity) : Array.Empty();
// Inferring from return type
IList<int> GetList(int capacity) {
return capacity > 0 ? new List<int>(capacity) : Array.Empty();
}
C#
// Inferring from declared variable type
IList<int> list = capacity > 0 ? new List<int>(capacity) : (IList<int>)Array.Empty();
// Inferring from return type
IList<int> GetList(int capacity) {
return capacity > 0 ? new List<int>(capacity) : (IList<int>)Array.Empty();
}