9

I was here idle, so I had this curiosity, Someone can tell me what's the maximum number of variables per method in C#?

Only a Curious Mind
  • 2,807
  • 23
  • 39

2 Answers2

20

I just tried to compile a generated program source with 26*26*26*26 local variables, not method parameters, (they were called @aaaa, @aaab, @aaac and so on), and I hit this limitation:

error CS0204: Only 65534 locals are allowed

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
5

There is no known limit on count of variables, also because any variable can have different size, but there is a memory limit on execution stack size.

Quoting Brian:

The default stack size for a .NET application is 1 MB (default is 256 KB for 32-bit ASP.NET apps and 512 KB for 64-bit ASP.NET apps), but you can change that. For the application you can change the default size by modifying the PE header of the executable. For threads you create, you can use the constructor overload that takes a stack size.

Stack capacity in C#

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 3
    I tried making a method with more than 65534 local variables (see my answer), and it could not compile. They were of reference type. 65535 references on the stack should not exceed 1 MB (but as I said it failed already at compile-time). This was the Visual C# compiler that comes with VS2012 (that's C# 5). – Jeppe Stig Nielsen Mar 19 '14 at 12:50