The C# team posts answers to common questions and describes new language features
Q: In C++, it's possible to write a static method variable, and have a variable that can only be accessed from inside the method. C# doesn't provide this feature. Why?
A: 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]
"From the implementation point of view they're class static members that are scoped to a single method" -- Jerry
In C++ static function variables are instantiated the first time the function is called. The assignment can also only be called once. But I'm not sure how, either by having the assignment function static, inline, or both. (Should be written in More Effective C++ by Scott Meyers).
I absolutely agree with Jerry. Besides VB has them, so it's not due to GC difficulties or anything else. It also promotes encapsulation
C# does allow state scoped to a method in other contexts, autoproperties and events. I'd rather allow it with a warning, then the coders can set policies to control whether they want to allow it to compile or not.
in C# every thing is in class. It cannot have method like in c , c++ which does not belong to any class.Hence there is no point in using static class method variables.
At any time we have an alternate to declare static member variable for that method
public void fun1()
static int count =0; //oops its an error in c#
public void fun2()
For this we can always have alternate like
static int fun1_count =0;
static int fun2_count =0;
yes, we can use a class level variable (private),
but a method-level static is really nice for encapsulating things that are used for recursion implementation
you can use
public int GetTen()
const int ten = 10;
with that you have the "STATIC METHOD VARIABLE" if for some reazon you need to have that ugly line of code.
Those aren't reasons, they are ridiculous excuses. All declarations (including 'using') should be allowed everywhere, to allow for localization of reference ... uses of the same name (or other information) should be grouped as close together as possible.
" A method itself doesn't logically have state outside the period during which it's being called."
How about this for a good use. I would really like this to not be a global variable since i have lots of registry values to read.
shared bool some_value;
public static bool hasEverBeenConfigured
static bool readRegistry = true;
readRegistry = false;
some_value = readfromregistry;