Looking at the ??
definition it says when applied returns left operand if it is not null or the right operand. But why does this doesn't work?
int? i = null;
string s = i ?? "some string";
Is it required that nullable type matches the right operand type?
??
is a syntactic sugar (in this case) for the following logical statement.
int? i = null;
string s = null;
if (i != null)
{
s = i;
}
else
{
s = "some string";
}
Obviously, the compiler would NEVER accept this and it wouldn't compile since i cannot be implicitly cast to s. The compiler doesn't make an exception for null coalescing operators and it enforces the type requirement.
If you absolutely wanted to be able to use a null coalescing operator for mixed types in a single line, you would need to perform a type conversion via another method.
You can't simply call i.ToString()
since this returns an empty string instead of null if i
is null, causing an empty string to be assigned to s
instead of "some string". As a result, you would need something like the following generic extension method:
public static string ToNullableString<T>(this Nullable<T> nullable) where T : struct
{
return nullable == null ? null : nullable.ToString();
}
which could be used like so:
int? i = null;
string s = i.ToNullableString() ?? "some string";
s
would be assigned the value "some string" since the extension method would correctly preserve the nullable value, allowing the null coalescing operator to choose the non-null alternative.
As of C# 6, you can use a Null Propagation Operator to simplify assignment instead of needing an extension method.
int? i = null;
string s = i?.ToString() ?? "some string";
In the above, i
is checked for null and, if not null, .ToString()
is called and the result is assigned. Else, i
is evaluated to null which causes the null coalescing operator to take precedence and "some string" is assigned to s
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With