CSharp - Create Self-Referenced Generic Types

Introduction

The following code shows how to Self-Referenced Generic Types.

Demo

using System;

interface ISameEmployee<T>
{
    string Equals(T obj);
}
class Employee : ISameEmployee<Employee>
{
    string deptName;
    int employeeID;
    public Employee(string deptName, int employeeId)
    {//w  ww.j  av a2  s  . com
        this.deptName = deptName;
        this.employeeID = employeeId;
    }
    public string Equals(Employee obj)
    {
        if (obj == null)
        {
            return "Cannot Compare with a Null Object";
        }
        else
        {
            if (this.deptName == obj.deptName && this.employeeID ==
              obj.employeeID)
            {
                return "Same Employee";
            }
            else
            {
                return "Different Employee";
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Employee emp1 = new Employee("Maths", 1);
        Employee emp2 = new Employee("Maths", 2);
        Employee emp3 = new Employee("Comp. Sc.", 1);
        Employee emp4 = new Employee("Maths", 2);
        Employee emp5 = null;
        Console.WriteLine("Comparing Emp1 and Emp3 :{0}", emp1.Equals(emp3));
        Console.WriteLine("Comparing Emp2 and Emp4 :{0}", emp2.Equals(emp4));
        Console.WriteLine("Comparing Emp3 and Emp5 :{0}", emp3.Equals(emp5));
    }
}

Result

Related Topic