#1,036 – Specifying Multiple Type Parameter Constraints

When you specify a constraint for a type parameter, you can specify multiple constraints for a particular type parameter.  The constraints are separated by commas.

In the example below, the type parameter T must be substituted with a type that implements both IBark and ICloneable and that also implements a parameterless constructor.

    // Type parameter T must specify a type that:
    //   Implements IBark
    //   Implements ICloneable
    //   Defines a parameterless constructor
    public class PileOf<T> where T : IBark, ICloneable, new()
        private List<T> thePile = new List<T>();

        public PileOf()
            // Start with default dog
            thePile.Add(new T());

        public void Add(T thing)
            // Store quieter version of loud dogs
            if (thing.BarkVolume > 9)
                T quietGuy = (T)thing.Clone();
                quietGuy.BarkVolume = 1;

            // Bark when added
            thePile[thePile.Count - 1].Bark("Woof");