stex
stex

Reputation: 861

Create a new instance of a type given as parameter

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!

Upvotes: 7

Views: 22838

Answers (2)

JDC
JDC

Reputation: 1785

Personaly I like this syntax much more.

Public Class Test(Of T As {New})
    Public Shared Function GetInstance() As T
        Return New T
    End Function
End Class

Or if you want to limit the possible types:

Public Class Test(Of T As {New, MyObjectBase})
    Public Shared Function GetInstance() As T
        Return New T
    End Function
End Class

Upvotes: 18

M.A. Hanin
M.A. Hanin

Reputation: 8074

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

Upvotes: 18

Related Questions