#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");

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: