Why doesn't C# support local static variables like C does?

Because they screwed up, and left out a useful feature to suit themselves.

All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses.

Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb.

Loop scope static is useful and important in many cases.

Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.


The MSDN blog entry from 2004: Why doesn't C# support static method variables? deals with the exact question asked in the original post:

There are two reasons C# doesn't have this feature.

First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity.

Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it's harder to find the definitions.

[author: Eric Gunnerson]

(Same blog entry in the Microsoft's own archive. The Archive.org preserved the comments. Microsoft's archive didn't.)


State is generally part of an object or part of a type, not part of a method. (The exception being captured variables, of course.)

If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.

Tags:

C#

Static