Denis
Denis

Reputation: 12077

Shared/Static Variable Should Be Nothing but Isn't - what gives?

I have the following code:

Public Class TestClass
    Public Sub Main()
        If theGlobal IsNot Nothing Then Throw New Exception("What gives!")
    End Sub

    Private Shared theGlobal As Object = Nothing
    Private Shared ReadOnly Property Global
        Get
            If theGlobal Is Nothing Then
                theGlobal = New Object()
            End If

            Return theGlobal 
        End Get
    End Property
End Class

Am stumped... Why is theGlobal object NOT Nothing?

Upvotes: 0

Views: 157

Answers (2)

NickAldwin
NickAldwin

Reputation: 11744

I think you meant

If Global Is Nothing Then Throw New Exception("What gives!")

You have to access the Global property for the field to be initialized, according to your code.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500525

Assuming that's really your code, my guess is that you're running this in the debugger with a breakpoint, and the watch window is evaluating the property, which is initializing theGlobal.

Just a guess, based on what I've seen before in similar situations.

If that doesn't help, try to write a short but complete console application which reproduces the problem, and which we can all run.

Upvotes: 5

Related Questions