persistant variables with local scope?

  • Thread starter Thread starter Michael Roper
  • Start date Start date
M

Michael Roper

Is there a C# approach that allows you to define locals with program
lifetime? That is, I don't want to have to expand the scope of a variable
just so I can make it persistent.

For example, something like:

class myClass
{
int iCallCounter = 0;
int CallCounter() { return ++iCallCounter }
 
Michael Roper said:
Is there a C# approach that allows you to define locals with program
lifetime? That is, I don't want to have to expand the scope of a variable
just so I can make it persistent.
No other approach, you have to make it a class variable.
Is there an elegant way to do this in the C# world?

The most elegant is to use a naming convention that helps define that a var
is only to be used by that method. I start the var with the same name as
the method, maybe something like below. This helps to keep a variable
assoicated with a method it "belongs" to.

class myClass
{
int callCounterIndex = 0;
int CallCounter() { return ++iCallCounter }

bool anotherMethodHasBeenRun = false;
void anotherMethod ()
{
if (!anotherMethodHasBeenRun)
{ blah; }
anotherMethodHasBeenRun = true;
}
}
 
Michael Roper said:
Thanks Michael. Is there a good reason this was left out of the language?
Seems odd not to make scope and lifetime independent attributes where it
makes sense to do so. Is it that information hiding is not considered as
important as lifetime, or am I missing the big picture?

I agree with you that it seems odd to be missing (but that's just my C++
heritage talking). I'm sure a lot of people from the Java camp would make
comments about the language being simpler this way. Classes hold state, not
methods, etc. If you do a google search within this newsgroup for "static
local variable" you'll find many threads on this topic. I suppose a very
similar case is variables that are tied to just a property, but not
class-wide.

The language has many mechanisms to help you encapsulate date (hide it) from
the "outside" world. There are very few mechanisms for futher encapsulating
data within a class from other parts of the class. If your classes are
small enough and simple enough, you shouldn't have too many problems just
letting your variables be class-wide. When your classes start to get big
and are developed by many developers, that's when it would be nice to have
some ways to hide data better. I suppose the only thing we can do now is to
try to keep classes as simple as possible.
 
Michael Mayer said:
I agree with you that it seems odd to be missing (but that's just my C++
heritage talking). I'm sure a lot of people from the Java camp would make
comments about the language being simpler this way. Classes hold state, not
methods, etc.

The latter is precisely the reason, which happens to lead to the
former.

You're essentially wanting state associated with an instance or with
the type itself, so declare it that way.
 
Back
Top