Working with System.Type and new

Posted on 2004-11-19
Medium Priority
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

Accepted Solution

NipNFriar_Tuck earned 2000 total points
ID: 12630717
What you would have to do is something like...

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


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses
Course of the Month17 days, 1 hour left to enroll

864 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