int foo;
int? bar;
if (bar != null)
{
foo = bar; // does not compile
foo = (int)bar; // compiles
foo = bar.Value; // compiles
}
I've known for a long time that the first statement is incorrect, but it has always bugged me. I've verified that bar
is not null, so why does the compiler complain?
The comparison is only saying - it is not null
, Compiler still uses type to see if the assignment can be made.
Following would compile even without null checking.
foo = (int)bar;
The type of bar
is still int?
, and there's no implicit conversion from int?
to int
.
The condition doesn't change the validity of the later code. The same is true for other casts:
object x = ...;
if (x is string)
{
string y = x; // This is still invalid
string z = (string) x; // This is fine
}
The compiler rarely uses the result of one piece of code to affect the validity of another. As another example:
bool condition = ...;
string x;
if (condition)
{
x = "yes";
}
if (!condition)
{
x = "no";
}
Console.WriteLine(x); // Invalid
The last line is invalid because x
still isn't definitely assigned. We know that whatever the value of x
, we'll enter one of those if
statement bodies... but the compiler doesn't try to figure this out.
Although this may seem dumb, it makes the language rules significantly simpler.
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