#547 – Things That Can Serve as Type Parameter Constraints

A constraint on a type parameter is often a base class or interface, but can actually take on a number of different forms.

A constraint can be a class type:

    // Type parameter can be some subclass of DogToy,
    // e.g. SqueakyToy, RopeToy
    public class Dog
        where TFavThing: DogToy

Or an interface type:

    public class Dog
        where TFavThing: IBuryable

Or another type parameter:

    // TFavThing must implement IBuryable
    // TOtherThing must be castable to TFavThing's type
    public class Dog<TFavThing,TOtherThing>
        where TFavThing: IBuryable
        where TOtherThing: TFavThing

class indicates that the type must be a reference type.

    public class Dog<TFavThing>
        where TFavThing: class

struct indicates that the type must be a non-nullable value type.

    public class Dog<TFavThing>
        where TFavThing: struct

new() indicates that the type must have a public parameterless constructor defined.

public class Dog<TFavThing>
    where TFavThing: new()
Advertisement

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

One Response to #547 – Things That Can Serve as Type Parameter Constraints

  1. Pingback: #1,141 – Reference Equality Used Even when Overload Available for Typed Parameter | 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 )

Connecting to %s

%d bloggers like this: