Static variables in methods
-
How can I define a static variable in a method for example like this:
private method() { static int c=0; c++; }
-
How can I define a static variable in a method for example like this:
private method() { static int c=0; c++; }
You can't; it's not allowed in C#. (Anyone know why?) The workaround is to declare your static variable as a field.
static int c=0; private method() { c++; }
Regards, Alvaro
He who laughs last, thinks slowest.
-
How can I define a static variable in a method for example like this:
private method() { static int c=0; c++; }
You can't. Static variables belong to an entire class, not a method. To define a variable inside a static method, just leave out the word 'static'. I remember programming in LotusScript, an old VB-based language. You could define a static function, and any variable declared in the function would be kept around for the next invocation of the function. C# doesn't work like that. Regards, Jeff Varszegi
-
How can I define a static variable in a method for example like this:
private method() { static int c=0; c++; }
-
You can't; it's not allowed in C#. (Anyone know why?) The workaround is to declare your static variable as a field.
static int c=0; private method() { c++; }
Regards, Alvaro
He who laughs last, thinks slowest.
IMHO it was taken out because it was a dumb idea and easily screwed up Jared jparsons@jparsons.org www.prism.gatech.edu/~gte477n
-
IMHO it was taken out because it was a dumb idea and easily screwed up Jared jparsons@jparsons.org www.prism.gatech.edu/~gte477n
Hmmm, the strange thing is that it's also not allowed in Java. I wonder if there's a correlation... jparsons wrote: it was a dumb idea and easily screwed up I don't consider it a dumb idea. There are times when it's nice to hold on to a value that only applies to a specific method. The problem may lie in the fact that static variables are initialized only once, so they can cause confusion:
void foo()
{
static int n = 0;
...
}When you see a method like that in C++, you need to keep in mind that the statement is only executed the first time the method is called. The casual (or careless) observer may not be aware of that, and erroneously think the method executes every time -- I'm pretty sure it's happened to me before :-O. Regards, Alvaro
He who laughs last, thinks slowest.