Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# programming style question - Assignment of Null Before Real Assignment [closed]

Is there a good reason (advantage) for programming this style

XmlDocument doc = null;
doc = xmlDocuments[3];

vs

XmlDocument doc = xmlDocuments[3];

I have seen it many times but to me it just seem overly verbose

like image 754
terjetyl Avatar asked May 13 '09 09:05

terjetyl


3 Answers

No - it's generally considered best practice to declare a variable as late as you can, preferably setting it at the point of declaration. The only time when I don't do that is when I have to set a variable conditionally, or it's set in a more restrictive scope:

String name;
using (TextReader reader = ...)
{
    // I can't declare name here, because otherwise it isn't
    // accessible afterwards
    name = reader.ReadToEnd();
}

Reasons for declaring at the point of first use where possible:

  • It keeps the variable's type close to its use - no need to scroll back up in the method to find it.
  • It keeps the scope as narrow as possible, which makes the use of the variable more obvious.
like image 146
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


I would use

XmlDocument doc = xmlDocuments[3];

Declare variables where they are used.

like image 33
Mitch Wheat Avatar answered Oct 06 '22 00:10

Mitch Wheat


They are different styles, and neither of them is objectivily better than the other. It's just a matter of taste. You can either declare the variable first and then assign a value to it:

XmlDocument doc;
doc = xmlDocuments[3];

Or you can do both in the same statement:

XmlDocument doc = xmlDocuments[3];

However, this form:

XmlDocument doc = null;
doc = xmlDocuments[3];

To assign a null reference to the variable and then immediately replace it with a different reference, is totally pointless.

like image 25
Guffa Avatar answered Oct 06 '22 01:10

Guffa