Tal Segal
Tal Segal

Reputation: 2835

Generics: how to implement: "where T derives from xxx"

I would like to use a generic class and force one of it's parameters to derive from some base class. Something like:

public class BaseClass { }
public class DerivedClass : BaseClass { }          
public class Manager<T> where T : derivesfrom(BaseClass)

The way I'm doing it now is at runtime in the constructor:

public class Manager<T> where T : class
{
    public Manager()
    {
        if (!typeof(T).IsSubclassOf(typeof(BaseClass)))
        {
            throw new Exception("Manager: Should not be here: The generic type should derive from BaseClass");
        }
    }
}

Is there a way to do this at compilation time ? Thank you.

Upvotes: 2

Views: 397

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178810

You almost had it:

public class Manager<T> where T : BaseClass

Read all about generic constraints here.

Upvotes: 12

Related Questions