TheDeveloperBlog.com


C# Multiple Local Variable Declarations

Multiple locals. A single statement can assign multiple local variables. Languages derived from C-style syntax often allow you to use commas to declare multiple variables in one statement. The C# language allows this.


Example. Let's introduce a program that uses the multiple local variable declarator syntax. In this syntax, you can declare and optionally assign several variables in a single statement. The comma character separates the variable declarators.

Note: The type of all of the variables declared or assigned this way is the same in a single statement.

C# program that initializes multiple variables

using System;

class Program
{
    static void Main()
    {
	//
	// Declare and initialize three local variables with same type.
	// ... The type int is used for all three variables.
	//
	int i = 5, y = 10, x = 100;
	Console.WriteLine("{0} {1} {2}", i, y, x);
	//
	// Declare and initialize three constant strings.
	//
	const string s = "dot", a = "net", m = "perls";
	Console.WriteLine("{0} {1} {2}", s, a, m);
	//
	// Declare three variables.
	// ... We initialize one of them.
	//
	int j = 1, k, z;
	Console.WriteLine(j);
	k = z = 0; // Initialize the others
	Console.WriteLine("{0} {1}", k, z);
    }
}

Output

5 10 100
dot net perls
1
0 0

In this example, the Main method body contains three local variable declaration lines. The first section declares and assigns three int locals. The second section declares and assigns three constant string literal references.

String Literal

Also: The final section declares three local ints but only assigns one of them.

Int

Note: Some programming guidelines discourage this syntax as it is somewhat unusual. In these situations, it should be avoided.

Instead: It is easier and more consistent to declare and assign one variable on each line.


Discussion. Let us consider how the execution engine allocates memory for local variables. Whenever a method is called, it is pushed onto the stack frame and three different spaces of memory are allocated.

So: All the local variables used throughout the method are allocated in one memory space.

And: The evaluation stack and parameter slots are separately allocated. They are not part of the local variable memory.

In other words, the count of variables can impact the performance hit when calling a method. An excellent description of this concept is found in Serge Lidin's book Expert .NET IL Assembler.


Summary. We looked at the multiple local variable declaration and assignment syntax. This syntax allows you to condense the syntax of variable declarations in your method bodies. Each statement list can have only one type name.