Req10: share variables in method bodies

[This post is part of a series, "wish-list for future versions of VB"]

 

VB's "static variables" are a powerful and useful time-saver. They declare a variable with a one-off initialization which is shared amongst all invocations of a instance's method. For example, here's how you might declare a lazy singleton-per-instance:

    Public ReadOnly Property Engine As AnalysisEngine

        Get

            Static _engine As AnalysisEngine = AnalysisEngine.ExpensiveCreateFunction()

            Return _engine

        End Get

    End Property

Without static variables, people have to code the same thing manually, and they usually get it wrong (the error in this case is that it's not thread-safe):

    private AnalysisEngine _engine;

    public AnalysisEngine Engine

    {

        get

        {

            return _engine ?? (_engine = AnalysisEngine.ExpensiveCreateFunction());

        }

    }

 

IDEA: Call them "shared variables" instead of "static variables".  The grounds for this idea is that they are "shared between all invocations of an instance's method".

 

IDEA: Allow "shared per delegate" variables inside a lambda. VB already has the notion of static variables that are "shared between all invocations of an instance's method". It should also introduce a new notion, lambda-shared variables, that are "shared between every invocation of a given delegate",

        Dim g = Function()

  Shared y As Integer = 2 ' shared amongst all invocations of this particular delegate

                    Console.WriteLine(y)

                    y += 1

                End Function

 

 

Provisional evaluation from VB team: Too confusing. Currently, "shared" unambiguously means "shared between all instances of a class". Static variables are not the same (unless they happen to be declared in a shared method). The lambda idea might be powerful but it's also too confusing. Someone reading your code shouldn't need the language-spec to hand just to understand which flavour of "shared" you're talking about.

 

asdasd

        Static x As Integer = 1

asdasd

adsad