Reputation: 75585
That is, in C, we can define a function like:
func(){
static int foo = 1;
foo++;
return foo;
}
and it will return a higher number every time it is called. Is there an equivalent keyword in C#?
Upvotes: 11
Views: 402
Reputation: 68707
public class Foo
{
static int _bar = 1;
public int Bar()
{
return ++_bar;
}
}
Upvotes: 0
Reputation: 32438
You'd have to create a static or instance member variable of the class the method is in.
Upvotes: 1
Reputation: 1502376
No, there's no such thing in C#. All state that you want to persist across multiple method calls has to be in fields, either instance or static.
Except... if you capture the variable in a lambda expression or something like that. For example:
public Func<int> GetCounter()
{
int count = 0;
return () => count++;
}
Now you can use:
Func<int> counter = GetCounter();
Console.WriteLine(counter()); // Prints 0
Console.WriteLine(counter()); // Prints 1
Console.WriteLine(counter()); // Prints 2
Console.WriteLine(counter()); // Prints 3
Now of course you're only calling GetCounter()
once, but that "local variable" is certainly living on well beyond the lifetime you might have expected...
That may or may not be any use to you - it depends on what you're doing. But most of the time it really does make sense for an object to have its state in normal fields.
Upvotes: 17