Using? between nullable <int> and string

Looking for a definition ?? , he says that when applied, returns the left operand if it is not a null or regular operand. But why does this not work?

 int? i = null; string s = i ?? "some string"; 

Is a type with a null value required to match the type of a valid operand?

+5
source share
1 answer

?? is syntactic sugar (in this case) for the next logical operator.

 int? i = null; string s = null; if (i != null) { s = i; } else { s = "some string"; } 

Obviously, the compiler would NEVER agree with this, and it would not compile, since I cannot be implicitly passed to s. The compiler does not make an exception for operators with zero coalescence and fulfills the type requirement.

If you absolutely wanted to be able to use the null coalescence operator for mixed types on the same line, you would need to perform type conversion using another method.

You cannot just call i.ToString() , as this returns an empty string instead of null if i is null, resulting in an empty string assigned to s instead of "some string". As a result, you will need something like the following general extension method:

 public static string ToNullableString<T>(this Nullable<T> nullable) where T : struct { return nullable == null ? null : nullable.ToString(); } 

which can be used as follows:

 int? i = null; string s = i.ToNullableString() ?? "some string"; 

s will be assigned the value "some string" because the extension method will correctly store the value with a zero value, allowing the null coalescing operator to choose a non-zero alternative.

+7
source

All Articles