Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I call Form.Close() if it's not a static method

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?

like image 464
Jonas Stawski Avatar asked Jan 19 '12 17:01

Jonas Stawski


1 Answers

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

like image 195
vcsjones Avatar answered Sep 27 '22 20:09

vcsjones