Objects implicitly created in vb.net?

I support an application with VB.NET and C # components. I thought that these two languages ​​differ only in syntax, but I found a strange function in VB.NET that is not in C #.

In VB.NET, I have the following class:

Public Class bill_staff Inherits System.Windows.Forms.Form .... End Class 

If I want to use this class in C #, I do this:

 using (var frm = new bill_staff()) frm.ShowDialog(); 

However, in VB.NET code, the class can be used as follows:

 bill_staff.ShowDialog(); 

ShowDialog defined in the metadata as follows:

 Public Function ShowDialog() As System.Windows.Forms.DialogResult 

So, in VB.NET, you can call the instance method for the class. As far as I can tell, this implicitly creates a new instance of the class, and then calls the method on this object. In C #, this is not possible: static methods must be called in the class, and object objects must be called.

I can not find information about this on the Internet. What function is called, and is it good practice?

The project was originally converted from VB6 - is this some kind of weird inherited function?

+7
source share
2 answers

Yes, this is obsolete behavior. Classes did not display in VB until v4, before that Form1.Show was a way to display forms. To keep the previous code compatible (VB3 was also very popular), the old method was supported.

It is still supported in .NET as a legal means for displaying forms. This was originally added to simplify porting VB6 code to VB.NET. But also in order to make it easy to get something in VB - MS refers to it as functionality at your fingertips and similar phrases.

Basically, it provides ease of programming without understanding objects and OOP. Imagine the questions that we would have here if Form1.Show chose the error.

Explicit stimulus is the best method because it is object oriented and makes it less likely if your code will link - or create - a new Form2 when you really want to use an existing instance.

+10
source

For forms, VB creates a default instance for you backstage. for example, 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 

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 happens in VB for forms (classes that inherit from System.Windows.Forms.Form). Personally, I think this is a terrible “feature” of VB - it mixes the difference between class and instance.

+4
source

Source: https://habr.com/ru/post/958410/


All Articles