Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new instance of a type given as parameter

Tags:

vb.net

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!

like image 766
stex Avatar asked Mar 07 '10 15:03

stex


1 Answers

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
like image 108
M.A. Hanin Avatar answered Sep 21 '22 23:09

M.A. Hanin