#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();
        }
Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: