Reputation: 1021
I want to instantiate one of two classes, that inherit from the same parent, at runtime.
Here's the parent class. It has all of the properties that are common to the two children.
public class Applicant
{
public int ApplicantID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
//etc
}
The two classes that inherit from it have the properties that make them different
public class PilotApplicant : Applicant
{
public byte[] SSN { get; set; }
public string EthnicExplain { get; set; }
public byte[] CryptoKey { get; set; }
public byte[] CryptoIV { get; set; }
}
public class CMSApplicant : Applicant
{
public string LocationName { get; set; }
}
Here's what I want to do, or something like this:
switch (Host)
{
case "pilot":
currentApplicant = new PilotApplicant();
break;
case "cms":
currentApplicant = new CMSApplicant();
break;
}
currentApplicant.ApplicantID = Convert.ToInt32(oReader["ApplicantID"]);
currentApplicant.FirstName = oReader["FirstName"].ToString();
currentApplicant.LastName = oReader["LastName"].ToString();
currentApplicant.MiddleName = oReader["MiddleName"].ToString();
Basically I'm trying to avoid setting all of the properties individually for the classes because 99% of them are the same for both classes. Is there a way I can do this?
Upvotes: 1
Views: 66
Reputation: 156918
What you are doing is okay. Juse use the base class and tweak it a little:
//
// Use base class here
//
Applicant currentApplicant;
switch (Host)
{
case "pilot":
currentApplicant = new PilotApplicant();
// set values for pilot
break;
case "cms":
CMSApplicant cmsApplicant = new CMSApplicant();
currentApplicant = cmsApplicant;
cmsApplicant.LocationName = (string)oReader["LocationName"];
break;
default:
currentApplicant = null;
break;
}
Upvotes: 3