This is very strange, maybe someone can explain what’s happening, or this is a bug (though I tend to think that this is probably just something intricate about C#).
The following code throws the error “Cannot implicitly convert type ‘uint?’ to ‘uint’.”:
public void Test(UInt32? p)
{
UInt32 x = p;
}
However, this code works without error:
public void Test(UInt32? p)
{
UInt32 x = p ?? 1;
}
Huh? Why does this work? Why would the coalesce operator cause implicit conversion of UInt32? (nullable) to UInt32 (non-nullable), while the first error message says that there is no implicit conversion between those types?
Think of it this way.
Nullable<T>is a value type. Obviously, it can’t really be null. Thus, the expression:Is really syntactic sugar for this:
Similarly, the expression:
Is syntactic sugar for:
From the preceding, it’s clear that the expression
p ?? 1is actually evaluating to auint, which is why the code works without a cast.