I have the following class
public class AbstractJobDao<T> where T : IJob {
protected T buildJob() {
// create an IJob implementation instance based on the generic parameter
}
}
public class FullTimeJobDao : AbstractJobDao<FullTimeJob> {
}
public class InternshipDao : AbstractJobDao<Internship> {
}
Both FullTimeJob and Internship implement the IJob interface. I’d like the buildJob() method to be able to infer the generic in the Dao implementation class using reflection, and then create an instance of that type. Is there a way to do this using reflection in .NET 3.5?
If so, what should the line/lines of code look like in the buildJob() method?
EDIT — I think I’m not clear on my question. What I want is for when buildJob() is called inside of the FullTimeJobDao, to create an instance of FullTimeJob. When buildJob() is called from inside of InternshipDao, it should create an instance of Internship, based on the generic type as defined at the top of the class.
What you have should almost work, except you don’t require your generic argument to be instantiable. If you add that as a constraint, you should be able to use
new:Alternatively, if you have some reason why that constraint is not appropriate in your situation, you can use
Activator.CreateInstance: