Hi i’m having to learn VB.net for a new job having previously been a C# guy. I just come across an interesting feature of VB.net. I can reference objects on a second form that has not been instatiated!
So from Form1 i can get the text property of textbox1 on Form2 as follows
Dim txt As String = Form2.TextBox1.Text
Can anyone explain how this works? Are all forms instatiated at the start of the program and then their visibility is toggled throughout the program lifespan?
Forms in VB are a special case. The compiler generates a strongly-typed list of forms in the
My.Formsobject of theMynamespace. Each form is exposed as a propertyMy.Forms.TheNameOfTheForm. These properties always return valid instances – i.e. if a form hasn’t been instantiated before, it will when you first use the property.So far, so good.
But Microsoft also made the brain-dead (!) decision of importing the properties from the
My.Formsobject by default, everywhere, and there’s nothing you can do. Superficially, this is for backwards compatibility reasons to VB6 but that’s nonsense since VB7 (.NET 1.0) didn’t have this feature, it only came later.But just to clarify:
No, luckily not. They are instantiated the first time you access the property.