Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of ?? between Nullable<int> and string

Tags:

c#

nullable

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?

like image 213
Daniel Jabsøn Avatar asked Jun 04 '15 22:06

Daniel Jabsøn


1 Answers

?? 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.

like image 147
David L Avatar answered Sep 28 '22 09:09

David L