Using static local variables in lazy loading in VB.NET

I recently learned about using static local variables in VB.NET and wondered about its potential use in lazy loading properties.

Consider the following code example.

Public Class Foo
  Implements IFoo
End Class

Public Interface IFoo
End Interface

Public Class Bar

  Private _fooImplementation As IFoo
  Public ReadOnly Property FooImplementation As IFoo
    Get
      If _fooImplementation Is Nothing Then _fooImplementation = New Foo
      Return _fooImplementation
    End Get
  End Property
End Class

This will be the usual, simplified property of lazy loading. You can even use the generic Lazy class to get (as far as I know) the same behavior.

Now consider the property when using a static variable.

Public Class Bar

  Public ReadOnly Property FooImplementation As IFoo
    Get
      Static _fooImplementation as IFoo = New Foo
      Return _fooImplementation
    End Get
  End Property
End Class

As far as I can see, this has several advantages over the usual implementation, first of all, your inability to access the variable outside the property, and also not to use the additional variable.

: - "" ? , , , , , , ? "" ? ?

.

+5
2

Static , IL . , , , . , . , , , . Static , Try/finally.

.NET 4, Lazy (Of T).

+3

, ... VB.NET static. # equivilent:

public class Bar
  {
    [SpecialName]
    private IFoo \u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation;
    [SpecialName]
    private StaticLocalInitFlag \u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init;

    public IFoo FooImplementation
    {
      get
      {
        Monitor.Enter((object) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init);
        try
        {
          if ((int) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State == 0)
          {
            this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State = (short) 2;
            this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation = (IFoo) new Foo();
          }
          else if ((int) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State == 2)
            throw new IncompleteInitialization();
        }
        finally
        {
          this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State = (short) 1;
          Monitor.Exit((object) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init);
        }
        return this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation;
      }
    }

    [DebuggerNonUserCode]
    public Bar()
    {
      this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init = new StaticLocalInitFlag();
    }
  }
+1

All Articles