static

  • Thread starter Thread starter TonyJ
  • Start date Start date
T

TonyJ

Hello!

This row below is from the documentation for C++.
A variable declared static in a function retains its state between calls to
that function.

How do I accomplish the above functionality in C#.

If I for example have an eventhandler that is called every 5 seconds I want
to keep some conters between these calls.

//Tony
 
TonyJ said:
This row below is from the documentation for C++.
A variable declared static in a function retains its state between calls to
that function.

How do I accomplish the above functionality in C#.

If I for example have an eventhandler that is called every 5 seconds I want
to keep some conters between these calls.

So you need to keep state in the object which contains the method. You
keep state in an object by declaring instance variables.
 
This row below is from the documentation for C++.
A variable declared static in a function retains its state between calls
to
that function.

How do I accomplish the above functionality in C#.

You don't. C# doesn't have static local variables. You need to keep the
state somewhere else, such as a static or instance member of your class.

Static state specific to a single method is almost always a bad idea
anyway. There's a very good chance that if you are wanting to do this,
your design is in want of improvement. For example, perhaps it would make
more sense for the method to actually be a part of some helper class,
maybe even a nested class, where it's more clear that some state is being
preserved and why.

There are exceptions, of course, but they are very infrequent. Usually
some persistent state belongs in the class anyway, being more a property
of the class or an instance of the class, than of a particular method.

Pete
 
With a field:

private int counter;
public void SomeMethod() {
counter++;
//whatever
}

If you want the method and field to apply to the type rather than the
instance, then mark both as "static".

Marc
 
With a field:

private int counter;
public void SomeMethod() {
  counter++;
  //whatever

}

If you want the method and field to apply to the type rather than the
instance, then mark both as "static".

Marc

I dont think that is quite right... what was that? the //whatever I
got...

making a class with get/set and using that instantiated class as a
static (c++ think) is along the line to go as suggested above, not
tested as usual
//CY
 
I dont think that is quite right... what was that? the //whatever I
got...

making a class with get/set and using that instantiated class as a
static (c++ think) is along the line to go as suggested above, not
tested as usual

No, Marc's absolutely right. A static variable within a method in C++
is basically a way of preserving state across method calls. That
corresponds directly with a static/instance field (depending on whether
the method is static or not) in C#.
 
Back
Top