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?
Local variables have no default value. Part of the language.
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.
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