I am maintaining an application that has both VB.NET and c# components. I thought these two languages differed only in syntax, but I have found a strange feature in VB.NET t
For forms, VB creates a default instance for you behind the scenes. e.g., the following VB:
Public Class bill_staff
Inherits System.Windows.Forms.Form
End Class
class testclass
sub testmethod()
bill_staff.Show()
end sub
end class
is equivalent to the following C#:
public class bill_staff : System.Windows.Forms.Form
{
private static bill_staff _DefaultInstance;
public static bill_staff DefaultInstance
{
get
{
if (_DefaultInstance == null)
_DefaultInstance = new bill_staff();
return _DefaultInstance;
}
}
}
internal class testclass
{
public void testmethod()
{
bill_staff.DefaultInstance.Show();
}
}
This only occurs in VB for forms (classes which inherit from System.Windows.Forms.Form). Personally, I think this is a terrible 'feature' of VB - it confuses the distinction between class and instance.
Yes that is legacy behavior. Classes did not show up in VB until v4, before that Form1.Show
was The Way to show forms. In order to keep previous code compatible (VB3 was also very popular), the old method was maintained.
It is still supported in .NET as a legal means to show forms. Initially, this was added to make it easy to migrate VB6 code to VB.NET. But is also there to make it easy to get something running in VB - MS refers to it as functionality at your fingertips and similar phrases.
Basically, it provides the tinkerer an easy way to program without understanding Objects and OOP. Imagine the questions we would have here if Form1.Show
threw an error.
Explicit instancing is the better method because it is object oriented and makes it less likely your code will reference - or create - a new Form2
when you actually wanted to use an existing instance.