2

If I make a new Windows Forms project and add a second Form (Form2), I can show the implicitly created form simply by referring to the class name:

Form2.Show()

If I look up the definition of Form.Show procedure, it is not listed as a Shared member of the Form class. How is it that I am able to call Show() on the Form2 class name?

Steve M
  • 9,296
  • 11
  • 49
  • 98
  • are you sure you don't have an instance? – Daniel A. White Jul 28 '14 at 01:11
  • @DanielA.White If I hover over the name where I call it, it says "Class Form2", if I however a name of an instance i created with New(), it says "Dim AForm As WindowsApplication1.Form2". So, it's not an instance unless the IDE is not accurate. – Steve M Jul 28 '14 at 01:14
  • possible duplicate of [When are default form instances created on application startup?](http://stackoverflow.com/questions/24906660/when-are-default-form-instances-created-on-application-startup) – Ňɏssa Pøngjǣrdenlarp Jul 28 '14 at 11:20

1 Answers1

3

I tried it, and then decompiled the executable with ILSpy.

It seems to be silently rewriting Form2.Show() into MyProject.Forms.Form2.Show() instead.

MyProject.Forms is a generated class that encapsulates a lazy-instantiated singleton instance of each form in the project.

This appears to be a feature of the IDE rather than the compiler, because in LINQPad, I get "Reference to a non-shared member requires an object reference."

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • There must be more to it that just a lazily-initialised singleton instance. I'd expect it to also be thread-static leading to all kinds of problems when people try things like `Form1.Invoke(...)` from a non-UI thread. – Kirill Shlenskiy Jul 28 '14 at 01:49
  • Yes, there is more to it, that was the 30 second glance summary. Looks like you're correct about thread-static anyway. Also see related question for some more discussion: http://stackoverflow.com/questions/4698538/why-is-there-is-a-default-instance-of-every-form-in-vb-net-but-not-in-c – Blorgbeard Jul 28 '14 at 01:59