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

Can someone explain this to me?

In Visual Studio 2010, create a VB.net Windows Forms application. Add 2 forms: Form1 and Form2. In Form1 Load, the event type is Form2.Close (). Now, if we look at the definition of a method, then Close () is not a static (general) method. So, how is it possible to compile or work at runtime.

Also, do the same in C # and Form2.Close (); not compiled.

What's happening? Why is this possible in VB.net and what actually happens when this line of code is executed?

+5
source share
3 answers

You have discovered a VB.NET-ism called the "default instance".

The compiler really emits this:

My.Forms.Form2.Close();

:

, VB.

...

, . My.Forms

+6

, VB , , , .

, , .

"" , " " , . , .

+5

You are right, you cannot call Form2.Close();when Form2- it is only a class type. However, VB.NET creates a property with the same name behind the scenes, and so you really call Closeon the instance Form2. You can do the same in C # by manually creating such a property. This is similar to calling a static method, but it is not.

+1
source

All Articles