Peter Goodman bio photo

Peter Goodman

A software engineer and leader living in Auckland building products and teams. Originally from Derry, 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!