A method can have only 65534 local variables. In the .NET Framework, local variables are stored in special local variable slots that are allocated upon method entry. There can only be 65534 local variables—which means they can be indexed with a two-byte unsigned integer.

This C# program determines the number of local variables allowed.

First, the program shown in this article is intended to generate 65535 local variable declarations and initializations into a text file. The point is to take these declarations, paste them into another C# program, and then see the compile-time errors generated by this. In this way, we can prove some aspects of the .NET runtime through experimentation.
Program that generates C# code [C#]
using System.IO;
class Program
{
static void Main()
{
// This program generates a file with 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 + ";");
}
}
}
Description. The point of this program is to generate to the text file "out" 65535 variable declaration statements in C# code. Each variable is of type integer. The goal is to then paste these assignments into a new C# method, and see the errors that Visual Studio yields when trying to compile that C# program.
Resulting execution in Visual Studio. This part describes my experience running the resulting program with the declarations in Visual Studio. The program was highlighted correctly in the IDE, but after the screenshot of the error was taken, the environment froze for 1:58 (almost two minutes), and Visual Studio expanded to 372,678K memory usage, nearly 400 megabytes.

Local variable slots. Some of the 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. Local variables are stored in a special memory allocation of local variable slots.
Here we looked at the maximum number of local variables that are allowed in C# programs targeting the .NET Framework on a 32-bit Windows operating system. In this experiment, each local variable can be conceptually accessed using a two-byte unsigned integer value. This test helps us determine some aspects of how the .NET Framework works, but the code is not useful in deployed applications.
Method Tips