#1,042 – Deriving from a Self-Referencing Constructed Type, Part I

When defining a type, the type can derive from a constructed generic type.

public class DogList : List<string>

You can use the name of the type being defined as the type argument to the type (or interface) that you’re deriving from.

Below, the Dog type is an argument to the IComparable generic interface.  We’re saying that we want Dog to implement IComparable<T> and it makes sense that the argument should be Dog.

    public class Dog : IComparable<Dog>
        public string Name { get; set; }
        public int WoofPower { get; set; }

        public Dog(string name, int woofPower)
            Name = name;
            WoofPower = woofPower;

        public int CompareTo(Dog other)
            // Returns
            //   < 0 if this < other
            //   0 is this == other
            //     > 0 if this > other
            return this.WoofPower - other.WoofPower;

Using Dog:

            Dog fido = new Dog("Fido", 4);
            Dog bowser = new Dog("Bowser", 9);

            int compare = fido.CompareTo(bowser);

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: