Question

Is the C# best practice to declare all local variables at the top of the method or to declare them right at their first use?

Example 1:

void myMethod()
{
    var example = String.Empty;
    var xmlDoc = new XmlDocument();

    xmlDoc.LoadXml("c:\my.xml");
    example = doc.SelectSingleNode("//TestNode").OuterXml;
}

Example 2:

void myMethod()
{
    var xmlDoc = new XmlDocument();

    xmlDoc.LoadXml("c:\my.xml");
    var example = doc.SelectSingleNode("//TestNode").OuterXml;
}
Was it helpful?

Solution

Historically, variables were declared up front in many languages because you had to instruct the compiler up front to associate registers and/or allocate space for them on the stack. In .NET, this is actually still required in the IL code, as it makes the compiler's job easier.

Thankfully C# is much higher level than IL, so we don't have to worry about those details. Freed from that constraint, there is a lot of conceptual value in limiting the scope of variables, as it means there is less code you have to look at to understand what happens to that variable. A variable declared at the top of a method can potentially be used anywhere in that method. A variable declared inside an inner 'if' is only used within that scope and you can ignore it once outside that scope; also, variables declared later in the method can only be used after their declaration. It's insulation/encapsulation in miniature, further reducing the number of things the developer has to think about at once to understand what a given piece of code is doing.

OTHER TIPS

I prefer your example 2, since it has fewer lines which generally means easier to read and fewer bugs.

For short methods (and all your methods are short, right?) it doesn't make that much difference.

But I would avoid unnecessary initialization of variables that you will alway subsequently set:

void myMethod()
{
    var example = String.Empty;  // Unnecessary initialization
    var xmlDoc = new XmlDocument();

    xmlDoc.LoadXml("c:\my.xml");
    example = doc.SelectSingleNode("//TestNode").OuterXml;
}

And avoiding this naturally leads you to declare variables where they're first initialized, i.e. your example 2.

Its just a personal preference, what ever is the easiest to read and understand.

I am use to declaring my variables at the start of the method because I'm use to doing it in C.

In C# declaring them at the start is my personal preference but C it was compulsory for me to declare them at the beginning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top