7

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!

stex
  • 861
  • 3
  • 13
  • 21

2 Answers2

18

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
M.A. Hanin
  • 8,044
  • 33
  • 51
  • @M.A. Hanin's answer is great, definitely use the generic version if you can. Instead of .Invoke(New Object()) I think you need to use .Invoke(Nothing). Also, all this said, 99% of the times I see someone doing this they're doing it for the wrong reason or are doing something the really, really hard way. Reflection is useful in a handful of situations but more often than not it just makes your code that much more confusing. – Chris Haas Mar 07 '10 at 16:24
  • This answer is exactly what I needed! I'm still trying to get http://stackoverflow.com/questions/2386690/method-to-override-shared-members-in-child-classes/2387070 working, so this seems to be a solution. – stex Mar 07 '10 at 17:11
  • @Stex, glad I could help. Concerning that other question, I'ev proposed another solution, but now I see that it might be irrelevant. @Chris Haas, thank you for your comment. I think you're right about those 99% - working with Generics and Reflection just seems too lucrative, though many times it turns out being an overkill / overcomplexation. – M.A. Hanin Mar 07 '10 at 17:23
18

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
JDC
  • 1,569
  • 16
  • 33