Reputation: 98
We came across this during problem determination within our code. We've fixed the bug, but the question remains:
Why is a reference to a non-shared member of a "Windows Form" allowed?
In order to replicate behaviour, create new Windows Forms application (I'm using VS2012, .net4.0), populate default form, Form1.vb, with:
Option Strict On
Option Explicit On
Public Class Form1
Private _private As String
Public ReadOnly Property NotSharedProperty As String
Get
Return _private
End Get
End Property
End Class
Then add a new class and call it PropertClass, fill it with:
Option Strict On
Option Explicit On
Public Class ProperClass
Private _private As String
Public ReadOnly Property NotSharedProperty As String
Get
Return _private
End Get
End Property
End Class
Then add another class, call it ExampleClass and fill it:
Option Strict On
Option Explicit On
Public Class ExampleClass
Public Sub New()
If Form1.NotSharedProperty Is Nothing Then
'.....................
End If
If ProperClass.NotSharedProperty Is Nothing Then
'.....................
End If
End Sub
End Class
In the ExampleClass, ProperClass.NotSharedProperty
gives me "Reference to a non-shared member requires an object reference." as one would expect. Form1.NotSharedProperty
does not. Why?
Upvotes: 0
Views: 202
Reputation: 63742
This is one of the many Visual Basic.NET compatibility features.
When you refer to a form by its type in old-school Visual Basic, you get the reference to a default instance of that form. That's just how VB development was done in the past (and VB wasn't the only environment that used this convention). Most of the time, you really only had one instance of each form.
Since you're not exploiting this feature on purpose, you probably never actually used the default instance, and your create your own instances as needed instead. In that case, Form1.NotSharedProperty
will simply return whatever the default is.
Upvotes: 2