Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an explicit conversion required after checking for null?

Tags:

c#

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?

like image 504
user247702 Avatar asked May 22 '13 12:05

user247702


2 Answers

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; 
like image 100
Habib Avatar answered Oct 14 '22 08:10

Habib


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.

like image 20
Jon Skeet Avatar answered Oct 14 '22 09:10

Jon Skeet