tags:

views:

39

answers:

1

Hi,

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!

+2  A: 

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
@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
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
@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