0

I have a Windows Forms application which has two forms: Form1 and Form2. The startup form is Form1, Form2 is loaded by a Button click.

After I load Form1, but before I load Form2, this is what I get:

MsgBox(Form2 Is Nothing) 'returns true
MsgBox(Form2.IsDisposed) 'returns false
MsgBox(Form2 Is Nothing) 'returns false 

Form2.Dispose()
MsgBox(Form2 Is Nothing) 'returns false
MsgBox(Form2.IsDisposed) 'returns false 

Form2.Close()
MsgBox(Form2 Is Nothing) 'returns false
MsgBox(Form2.IsDisposed) 'returns false 

If I load Form2 and then close it with a Close box:

MsgBox(Form2 Is Nothing) 'returns false
MsgBox(Form2.IsDisposed) 'returns false 

Why is Form2 never disposed of, and how one can completely dispose of it?

and his dog
  • 149
  • 7
  • 4
    You are talking about the _default form instance in vb.net_ Read more here https://stackoverflow.com/questions/4698538/why-is-there-a-default-instance-of-every-form-in-vb-net-but-not-in-c or this http://jmcilhinney.blogspot.com/2009/07/vbnet-default-form-instances.html – Steve Dec 15 '18 at 15:37
  • Nice to see my blog post being recommended as a resource on this subject. :-) In short, the form IS being disposed but checking whether it has been disposed creates a new one. Every time you put a dot after the form type name, a new instance is created if none exists OR one does exist but it has been disposed. That means that testing the `IsDisposed` property is actually creating a new instance and discarding the one that you previously disposed. – jmcilhinney Dec 16 '18 at 01:11
  • 2
    You'll find that very few experienced developers use default instances and many (most?) dislike them because they actually cause as much confusion as they help. This question is a case in point. Microsoft has never said so but most seem to suspect that default instances were added in VB 2005 to make migrating VB6 developers feel more at home, because they behave much as forms do in VB6. They are useful if you want singleton behaviour from a form but useless otherwise. There's no reason not to treat forms like other types and you don't refer to instances of other types using the type name. – jmcilhinney Dec 16 '18 at 01:15

0 Answers0