static local variables

A

Avi Farah

Folks,

VB.Net allows a Function / Sub to have a static local
variable while C# does not. A local variable that keeps
it value from call to call. Does anyone know how I can
achieve the same functionality in C#?

If I cannot achieve the same in C# all is not lost since
the variable can easily be moved to be a private instance
variable of the class. Though its scope grew a bit.

Cheers,
Avi
 
J

Jon Skeet [C# MVP]

Avi Farah said:
VB.Net allows a Function / Sub to have a static local
variable while C# does not. A local variable that keeps
it value from call to call. Does anyone know how I can
achieve the same functionality in C#?

If I cannot achieve the same in C# all is not lost since
the variable can easily be moved to be a private instance
variable of the class. Though its scope grew a bit.

Just use a private instance variable. You can't do this in C# because
logically a method doesn't have state - only an object or a type does.

This is what VB.NET does under the cover as well, just hiding the name
appropriately.
 
S

Steve

Jon said:
Just use a private instance variable. You can't do this in C# because
logically a method doesn't have state - only an object or a type does.

This is what VB.NET does under the cover as well, just hiding the name
appropriately.

That will work? Are you sure, because the static does not have access to
an instance variable.
 
J

Jon Skeet [C# MVP]

Steve said:
That will work? Are you sure, because the static does not have access to
an instance variable.

If you want a "static local" variable within a static method, use a
private static variable. If you want a "static local" variable within
an instance method, use a private instance variable. Note the two
different uses of the word "static" here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top