vb.net windows forms question.
I’ve got 3 forms that have exactly the same functions, so I decided to create an interface.
public Interface IExample
public sub Add()
Public sub Edit()
Public sub View()
End Interface
Then I created the 3 forms, and added the ‘implements interface IExample’ to each.
public class frmExample1
implements Interface IExample
Same for frmExample2, frmExample3
Finally, in code, I declare a variable of the interface type ..
Dim objfrmExample as IExample
then …
objFrmExample = frmExample2
At this point, objfrmExample is now instantiated, even though I’ve not done a “objfrmExpample = new [what-goes-here?] ” and I’m curious as to why.
I could possibly guess that because you cannot instantiate an interface variable, then vb.net automatically creates an instance. But thats just a guess. The question is , what is meant by declaring a variable of type Interface, and how does it work?
Anyway, just curious 🙂
This has nothing to do with interfaces. You can always treat a form class name in VB as though it were an instance. The reason is that the VB compiler creates properties of all your forms inside
My.Forms. Now you can access a “default” instance of each form by accessingMy.Forms.<FormName>.Now comes the ugly part: you can also omit
My.Forms.. In other words, whenever you write justFormNameand from the context it’s unambiguous that you need an instance rather than the class name, VB will act as though you’d writtenMy.Forms.<FormName>.Luckily, this only works for forms, not for any other classes. VB creates each default instance when you first access it. So as long as you don’t access a default instance, it’s not created. Once you access it for the first time, VB creates it and invokes its constructor.