merlin2011
merlin2011

Reputation: 75585

Does there exist a keyword in C# that would make local variables persist across multiple calls?

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

Answers (3)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

public class Foo
{
    static int _bar = 1;

    public int Bar()
    {
        return ++_bar;
    }
}

Upvotes: 0

George Duckett
George Duckett

Reputation: 32438

You'd have to create a static or instance member variable of the class the method is in.

Upvotes: 1

Jon Skeet
Jon Skeet

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

Related Questions