TheDeveloperBlog.com


C# Locals Allowed

Locals allowed. A method can have only 65534 local variables. Locals are stored in special slots that are allocated upon method entry. There can only be 65534 local variables. This means they can be indexed with a two-byte unsigned integer.

Ushort

Example. First, this program generates 65535 local variable declarations and initializations into a text file. The point is to take these declarations, paste them into another C# program. We then see the compile-time errors generated.

Note: In this way, we prove some behavior of the .NET Framework through experimentation.

C# program that generates code

using System.IO;

class Program
{
    static void Main()
    {
	// This program generates a file.
	// ... It contains thousands of local variable declarations.
	// ... You can paste it into a C# file later.
	using (StreamWriter writer = new StreamWriter("out"))
	for (int i = 0; i < ushort.MaxValue; i++)
	{
	    writer.WriteLine("int i" + i + " = " + i + ";");
	}
    }
}

The program writes to the text file "out" 65535 variable declaration statements in C# code. Each variable is of type integer. We then paste these assignments into a new C# method, and see the errors that Visual Studio yields.

Result: The program was correctly highlighted, but the environment froze for 1:58 (almost two minutes).

Also: Visual Studio expanded to 372,678K memory usage—this is nearly 400 megabytes.

Local variable slots. Some implementation details of the .NET Framework are relevant to the hard limit of local variables you can use. With the limit determined, each local variable can be indexed though a two-byte unsigned integer.

Note: Local variables are stored in a special memory allocation of local variable slots.


Summary. We determined the maximum number of local variables that are allowed in C# programs on a 32-bit Windows operating system. In this experiment, each local variable can be conceptually accessed using a two-byte unsigned integer value.

Thus: This test helps us determine some aspects of how the .NET Framework works, but the code is not useful in deployed applications.