Can someone explain this to me?
In Visual Studio 2010, create a VB.net Windows Forms App. Add 2 forms: Form1 and Form2. In the Form1 Load event type Form2.Close(). Now if we look in the method definition Close() is not a static (shared) method. So how is this possible to compile or to work at run time.
Furthermore, do the same thing in C# and Form2.Close(); doesn't compile.
What's going on? Why is this possible in VB.net and what is actually happening when that line of code is executed?
You've discovered a VB.NET-ism called "default instance".
The compiler is actually emitting this:
My.Forms.Form2.Close();
There is a nice writeup of that feature here:
The default instance is an object of that type that the VB application framework creates and manages for you.
...
If you use the default instance then you don’t need to invoke a constructor explicitly. You simply access the default instance directly via the My.Forms object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With