3

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?

1 Answer 1

5

Do you mind using reflection? If not:

if (typeof(T).IsClass) { Type targetType = typeof(Target<>).MakeGenericType(typeof(T)); return Activator.CreateInstance(targetType); } ... 

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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

Good idea. typeof(T).IsClass is already reflection - is it considerably faster than the new code?
@Kobi: typeof(T).IsClass will be pretty fast though, compared with the Activator.CreateInstance call. (At least, that's what I'd expect. If I really cared, I'd test of course :)
The two lines you added. He already had typeof(T).IsClass. Anyway, good answer, let us not dwell on this :). Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.