Self-Referencing Generic Declarations - CSharp Custom Type

CSharp examples for Custom Type:Generics

Introduction

A type can name itself as the concrete type when closing a type argument:

public interface IEquatable<T> { bool Equals (T obj); }

public class MyClass : IEquatable<MyClass>
{
  public string Color { get; set; }
  public int CC { get; set; }

  public bool Equals (MyClass b)
  {
      if (b == null) 
         return false;
      return b.Color == Color && b.CC == CC;
  }
}

The following are also legal:

class Foo<T> where T : IComparable<T> { ... }
class Bar<T> where T : Bar<T> { ... }

Related Tutorials