HeadMelter of the week - Self-Constrained Generic Base Classes

Melted my own brain for a few hours with this one today. Essentially a self-constrained generic base class looks like the following.

    public class MyEntity : EntityBase<MyEntity> {

    }

 

This allows me to put some generic implementations in a base class for code that I would simply duplicate otherwise. For example:

 

    public class EntityBase<T> : IEquatable<T>, IComparable<T>

    {

        public int CompareTo(T other) {

            // Insert compare code here

 

        }

 

        public bool Equals(T other) {

            // Insert Equality Code Here

        }

    }

 

Enjoy!

Print | posted @ Sunday, November 04, 2007 6:55 PM

Comments on this entry:

No comments posted yet.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 3 and type the answer here: