Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB6's private static in C#?

Tags:

java

c#

.net

vb6

In VB6 there are local static variables that keep their values after the exit of procedure. It's like using public vars but on local block. For example:

sub count()
static x as integer
x = x + 1
end sub

After 10 calls, x will be 10. I tried to search the same thing in .NET (and even Java) but there was none. Why? Does it break the OOP model in some way, and is there a way to emulate that.

like image 909
blez Avatar asked Apr 30 '10 22:04

blez


1 Answers

The closest you can get is a static field outside the method:

private static int x;
public [static] void Foo() {
    x++;
}

Closure example as requested:

using System;
class Program {
    private static readonly Action incrementCount;
    private static readonly Func<int> getCount;
    static Program() {
        int x = 0;
        incrementCount = () => x++;
        getCount = () => x;
    }
    public void Foo() {
        incrementCount();
        incrementCount();
        Console.WriteLine(getCount());
    }
    static void Main() {
        // show it working from an instance
        new Program().Foo();
    }
}
like image 192
Marc Gravell Avatar answered Sep 28 '22 23:09

Marc Gravell