I have a class, Target<T> that cannot be altered, with a generic constraint. I want to possibly build instances of that class from a generic class that has no constraint. The following demonstrates the intent of what I want to do, but I realize that this code will not compile and that typeof(T).IsClass is a runtime check and the generic constraints are compile-time concerns.
public class TargetMaker<T>
{
public object GetTarget()
{
if (typeof(T).IsClass)
{
return new Target<T>();
}
return default(T);
}
}
public class Target<T> where T : class
{
public Target() { }
}
Can anyone think of a way that I can achieve what I want here in TargetMaker without adding a matching constraint to it, while keeping all of the logic in the TargetMaker class?
Do you mind using reflection? If not:
If performance is a concern, there are probably ways of optimizing it – such as building factory delegates via expression trees, and caching them. That’s going to be a lot of hassle if performance isn’t a problem though 🙂