Finding a class type at runtime.

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
 
M

Mark Smithson

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.
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top