I've searched for an answer and found some c#-examples, but could not get this running in vb.net:
I thought of something like the following:
public function f(ByVal t as System.Type)
dim obj as t
dim a(2) as t
obj = new t
obj.someProperty = 1
a(0) = obj
obj = new t
obj.someProperty = 2
a(1) = obj
return a
End Function
I know, I can create a new instance with the Activator.Create... methods, but how to create an array of this type or just declare a new variable? (dim)
Thanks in advance!
It really depends on the type itself. If the type is a reference type and has an empty constructor (a constructor accepting zero arguments), the following code should create an insance of it: Using Generics:
Public Function f(Of T)() As T
Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {})
Return tmp
End Function
Using a type parameter:
Public Function f(ByVal t As System.Type) As Object
Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With