#544 – Specifying a Constraint for a Type Parameter

When you provide a type parameter to a generic class, you can only invoke methods in System.Object for objects of that type.

    public class Dog<TFavThing>
    {
        public void BuryThing(TFavThing thing)
        {
            // Err: TFavThing does not contain a definition for Bury
            thing.Bury();
        }

You can allow calling methods in a specific type by adding a constraint to the type parameter, indicating what type the parameter must conform to.  Adding a constraint lets you do two things:

  • Ensure that a type parameter belongs to a specific type
  • Allow you to call methods in a specific type, for objects whose type matches the type parameter

A constraint consists of a type parameter name following by an indication of the type that it must be.  (Generally a base class or an interface).

    // TFavThing type parameter must be a type that implements IBuryable
    public class Dog<TFavThing> where TFavThing: IBuryable
Advertisements

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.

3 Responses to #544 – Specifying a Constraint for a Type Parameter

  1. Pingback: #546 – Specifying More than One Constraint for the Same Type Parameter « 2,000 Things You Should Know About C#

  2. Pingback: #547 – Things That Can Serve as Type Parameter Constraints « 2,000 Things You Should Know About C#

  3. Pingback: #1,070 – A Generic Type Can Be Compiled | 2,000 Things You Should Know About C#

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: