Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Forcing" Conformance to a Generic Constraint

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?

like image 445
Erik Dietrich Avatar asked Mar 22 '26 10:03

Erik Dietrich


1 Answers

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

like image 65
Jon Skeet Avatar answered Mar 24 '26 23:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!