#1,038 – Type Parameter Constraints on Generic Methods

You can specify type parameter constraints for both generic types and generic methods.

The example below shows a type constraint for a generic type.

    public class MooPile<T> where T : IMoo
    {
        private List<T> mooPile = new List<T>();

        public void AddMooThing(T thing)
        {
            mooPile.Add(thing);
            mooPile[mooPile.Count - 1].Moo();
        }
    }

And below is a type constraint for a generic method (which happens to be defined within a non-generic class).

        static void SwapAndMoo<T>(ref T item1, ref T item2) where T : IMoo
        {
            T temp = item1;
            item1 = item2;
            item2 = temp;

            item1.Moo();
            item2.Moo();
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment