2

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.

Tal Segal
  • 2,735
  • 3
  • 21
  • 17

1 Answers1

12

You almost had it:

public class Manager<T> where T : BaseClass

Read all about generic constraints here.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393