views:

333

answers:

4

I am working on a VB.NET WinForms app that was "upgraded" by Visual Studio (originally 1.0 or 1.1) from VB6 code (which was itself upgraded from VB5). Except for the few new forms I've created since taking over maintenance of this app, all of the forms in the application have a method called DefInstance which allows you to grab an in-memory copy of the form if there is one. What I can't figure out is why: when would I ever need to reference a form object in memory when it's not immediately in scope where I'm working. To my mind this violates all kinds of sound programming principles and seems like an invitation for memory leaks or worse.

The questions: (1) is this DefInstance thing an merely unfortunate remnant of the VB6 heritage of this app, and (2) should I make a point of removing DefInstance methods throughout the application?

+1  A: 

As you mention, it lets you get a reference to the form.

I've seen lots of VB written like this:

Private Sub Command_Click()
   Call DoStuff
End Sub

Private Sub DoStuff()
   Form1.myTextbox.Text = "Bad Idea"
End Sub

DefInstance allows DoStuff() to continue working without passing controls around.

See here: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/6d7985b5-6db6-47a8-9e11-cbf114a48d37/ for more info.

BQ
+1  A: 

Sadly, that toxic bit of syntactic sugar was added to VB8 (VS2005). Now fatally confusing VB.NET programmers when they can't comprehend that each thread has a separate instance of "Form1". The good news: now you definitely don't need DefInstance anymore.

Hans Passant
A: 

I received this answer from a Microsoft employee:

http://msdn.microsoft.com/en-us/library/aa289529(VS.71,printer).aspx

In short, DefInstance is a "not best practices" compatibility method for older apps that haven't been made into true .NET WinForms apps. Being a web programmer until earlier this year I had never worked with VB6 "WinForms" applications nor had to deal with the compatibility compromises that the upgrade wizard makes in forcing them into .NET.

Parvenu74
A: 

In answer to your question: Yes, the default instance is a terrible byproduct of importing the application through the upgrade wizard. Using the default instance was a VB habit in pre dot net versions because forms were always resident in memmory as a default instance, although you could also g=create additional instances. As Parvenu74 said, it is not a best practise. That being said, you should be very careful when removing it from an imported application because of side affects and references where it might be being used. Your best bet is to not use it in new code that you develop and slowly migrate yourself away from the "converted" code over time. As was mentioned above the default instance stuff was re-instroduced in VB 2005, but it's use is highly discouraged.

Steve Massing