[2008] How do I make a new instance based on a variable's type?
Hey guys. I've been programming for a long time, but there's something I've never figured out how to do in all this time. Surely there is a way to turn the following code into a sub so I don't have the same boilerplate show form code in use a thousand times in a program:
Example:
Code:
Public InstanceOfFrmGeneric As frmGeneric
If InstanceOfFrmGeneric Is Nothing Then
InstanceOfFrmGeneric = New frmGeneric()
InstanceOfFrmGeneric.Show()
Else
If InstanceOfFrmGeneric.IsDisposed Then
InstanceOfFrmGeneric = New frmGeneric()
InstanceOfFrmGeneric.Show()
Else
InstanceOfFrmGeneric.Focus()
End If
End If
Basically, I need a way to do this provided the input of the form's instance variable. Ideally something like:
Code:
Private Sub showForm(ByRef InstanceOfForm As Form)
'Pseudo-code
If InstanceOfForm Is Nothing Then
InstanceOfForm = New Magic Thing Letting Me Make New Instance Of InstanceOfForm Based on Its Type Or Whatever
InstanceOfForm.Show()
Else
If InstanceOfForm.IsDisposed Then
InstanceOfForm = New New Magic Thing Letting Me Make New Instance Of InstanceOfForm Based on Its Type Or Whatever
InstanceOfForm.Show()
Else
InstanceOfForm.Focus()
End If
End If
End Sub
Anyone know how to do this? It's probably a simple Typing thing or something, but that's not an area I'm good at since it doesn't seem to flow with the normal language.
Re: [2008] How do I make a new instance based on a variable's type?
Hey,
Can you not implement a Singleton pattern in the Form definition.
Have a look here for details:
http://www.ondotnet.com/pub/a/dotnet...singleton.html
Gary
Re: [2008] How do I make a new instance based on a variable's type?
You could use a generic:
Code:
Private Sub showForm(Of t As Form)(ByRef InstanceOfForm As t)
'Pseudo-code
If InstanceOfForm Is Nothing Then
InstanceOfForm = DirectCast(Activator.CreateInstance(Of t)(), t)
InstanceOfForm.Show()
Else
If InstanceOfForm.IsDisposed Then
InstanceOfForm = DirectCast(Activator.CreateInstance(InstanceOfForm.GetType), t)
InstanceOfForm.Show()
Else
InstanceOfForm.Focus()
End If
End If
End Sub
Dim f As Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
showForm(Of Form2)(f)
End Sub
Re: [2008] How do I make a new instance based on a variable's type?
I tend to like Negative0s suggestion, but I thought I might suggest that you also look at GetType. The name property would hold the type name, though the only thing I can really think to do with that is to use it for a switch, which would be fine for just a few forms, but wouldn't be very extensible.
Re: [2008] How do I make a new instance based on a variable's type?
Thank you very much, folks. Two different and interesting solutions to accomplish the same goal. It works!
Activator.CreateInstance...I'm going to have to remember that one.