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?
Class field members get defaulted (value types each depending on its type, ref types to null) but local variables do not.
EDIT: This was designed to avoid C++ runtime errors which was causing the program to close unexpectedly (because of null pointers).
P.S: You may not downvote me when I talk about C# specs (I didn’t make C# specs, I cheer this avoidance though).