Peter Goodman bio photo

Peter Goodman

A developer living in Auckland building software using all sorts of bits and pieces I find along the way. Originally from Northern Ireland.

Twitter Google+ LinkedIn Github

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!