Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between null and not initialized?

When I write the following code in C#:

SqlCeCommand command;
try
{
    // The command used to affect the data
    command = new SqlCeCommand
                  { 
                     // init code removed for brevity
                  };

    // Do stuff 
    // Do more stuff
}
finally
{
    if (command != null)
        command.Dispose();
}

Resharper complains on my check of command != null. It says that command may not be assigned (because it could fail some how in the constructing and still hit the try block).

So I change the declaration of command to be SqlCeCommand command = null; and everyone is happy.

But I am left wondering what the difference is?

And why doesn't it just default to null? Meaning: How does C# benefit from not just defaulting local variables to null?

like image 478
Vaccano Avatar asked Feb 23 '11 20:02

Vaccano


2 Answers

Local variables have no default value. Part of the language.

like image 104
Ted Hopp Avatar answered Oct 10 '22 06:10

Ted Hopp


Well if you want it to be null then you need to tell it to. This is to catch bugs. The compiler and utilities like ReSharper searches all execution paths and makes sure that variables are initialized before they are being used. This is to catch common coding mistakes. So there is no additional "not even null" value possible, it is only an analysis done by the compiler (or whatever) to help you out.

Class members are initialized to default values (e.g. null for reference types), so there you get the behavior you expect.

like image 35
Anders Zommarin Avatar answered Oct 10 '22 06:10

Anders Zommarin