#545 – Specifying Constraints for More than One Type Parameter

When specifying constraints for type parameters in a generic class, you can specify constraints for more than one parameter.

To specify more than one constraint, just place each constraint on a separate line, with its own where clause.

    // TFavThing type parameter must be a type that implements IBuryable
    // TFavFood type parameter must be a type that implements IEdible
    public class Dog<TFavThing,TFavFood>
        where TFavThing: IBuryable
        where TFavFood: IEdible
    {
        public void BuryThing(TFavThing thing)
        {
            thing.Bury();
        }

        public void Eat(TFavFood eatThis)
        {
            eatThis.Eat();
        }
    }

When constructing this type, we just need to use types that implement the specified interfaces.

            // Bone implements IBuryable
            // RawFood implements IEdible
            Dog<Bone,RawFood> d = new Dog<Bone,RawFood>("Buster", 5);

            d.BuryThing(new Bone("Rawhide"));
            d.Eat(new RawFood(16));  // 16 oz chunk
Advertisements

#542 – Conventions for Naming Type Parameters

You can name type parameters in generic classes and generic methods anything you like.  But you should typically follow the following naming conventions for naming type parameters:

  • Use a short descriptive name
  • Use “T” as the first letter of the type parameter
  • Use “T” alone as the type parameter if it is the only parameter and if a longer name would not make its use more clear

Here are a couple examples from the .NET Framework source code:

    class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
    {
        IDictionary<TKey, TValue> dictionary;

        public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
            : this(dictionary, true)
        {

 

        public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array) {