Working with System.Type and new

Posted on 2004-11-19
Last Modified: 2010-04-15
Suppose I have these classes:

class MyBaseClass { ... }
class DerivedClass1 : MyBaseClass { ... };
class DerivedClass2 : MyBaseClass { ... };

And I have a function like this:

ArrayList GetAllInDatabaseLike(MyBaseClass template);

that you can pass an instance of one of the derived classes, and it will fill the array list filled with new objects of DerivedClass1 or DerivedClass2.

I.e., if you say

GetAllInDatabaseLike(new DerivedClass1); it will return an array list full of new DerivedClass1 objects filled with data from the database,

and if you say

GetAllInDatabaseLike(new DerivedClass2); it will return an array list full of new DerivedClass2 objects filled with data from the database.

How do I ensure that it is able to create objects of the correct derived (not base!) class?

Can I say something like:

ArrayList[2] = new typeof(template);

Or do I have to do something via System.Type?
Question by:CDFA_Inc
    1 Comment
    LVL 7

    Accepted Solution

    What you would have to do is something like...

    ArrayList[2] = Activator.CreateInstance( template.GetType() );


    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Suggested Solutions

    Article by: Ivo
    Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
    Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now