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
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:
I would use
XmlDocument doc = xmlDocuments[3];
Declare variables where they are used.
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.
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