Finding a class type at runtime.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

I have a class which holds a collection. The collection contains objects and at runtime all objects in the collection are of the same type. For example, the collection will hold cName classes, or cAddress classes.

What I can't figure out is how to create a new class of the same type as the first class in the collection.

For example, in the class holding the collection I have a method AddNew which needs to find out what type of classes the collection is holding (names, addresses, etc.), then create a new one and add it to the collection.

Any ideas are much appreciate, and thank you for your time reading this post.

Regards

Darren
 
Hi Darren,

If you get the first item from the collection you can get its type using

Type itemType = obj.GetType();

This type can then be used to create a new instance using
Activator.CreateInstance(itemType);

If your type takes constructor arguments you can pass these as an object
array in the second argument

Regards

Mark

Darren Wooding said:
Hi all,

I have a class which holds a collection. The collection contains objects
and at runtime all objects in the collection are of the same type. For
example, the collection will hold cName classes, or cAddress classes.
What I can't figure out is how to create a new class of the same type as
the first class in the collection.
For example, in the class holding the collection I have a method AddNew
which needs to find out what type of classes the collection is holding
(names, addresses, etc.), then create a new one and add it to the
collection.
 
Thanks Mark. Worked like a dream. The VB code is below in case anyone else needs it.

Dim itemtype As Type = colCollection.Item(1).GetType
Dim cLocal As Object = Activator.CreateInstance(itemtype)

Regards

Darren
 
Back
Top