Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create an object of unknown type???

Status
Not open for further replies.

ThankGodItsFriday

Programmer
May 12, 2005
11
SE
I have a number of classes that inherits from a baseclass.
The normal way to populate the object is to send it a DataRow containing the information needed.

But now I need a function that returns an ArrayList of objects that are derived from the baseclass. The function is not, nor can it be, in the baseclass or in the derived classes.
In order to make it as general as possible I'd like to populate it dynamically using a System.Type and an sqlstring - Like this:
Code:
public static ArrayList GetObjectList(Type objType, string sql)
{
   // Check that objType is a subclass of BaseClass
   if ( ! objType.IsSubclassOf(BaseClass) ) { Throw exception}
   ArrayList al = new ArrayList();
   BaseClass tmpObj;
   DataTable table = GetDataTable(sql);
   foreach (DataRow dr in table.Rows)
   {
      // Here I need to typecast tmpObj to a new object of the type provided by objType and pass dr to the constructor
       al.Add(tmpObj);
   }
}

I know that I can solve this with a switch/case statement on objType, but that would break encapsulation as this object would have to know all the classes that inherits BaseClass.

Any suggestions on solutions and/or articles/googles/whatever are welcome.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top