CSharp - Add Generic Constraints

Introduction

Consider the following program and output, and then follow the analysis.

Demo

using System;
using System.Collections.Generic;

interface IEmployee
{
    string Position();
}
class Employee : IEmployee
{
    public string Name;
    public int yearOfExp;
    public Employee(string name, int years)
    {//from w  w  w .  j  a  v  a2  s  .co  m
        this.Name = name;
        this.yearOfExp = years;
    }
    public string Position()
    {
        if (yearOfExp < 5)
        {
            return " A Junior Employee";
        }
        else
        {
            return " A Senior Employee";
        }
    }
}
class EmpList<Employee> where Employee : IEmployee
{
    private List<Employee> MyStore = new List<Employee>();
    public void AddToStore(Employee element)
    {
        MyStore.Add(element);
    }
    public void DisplaySore()
    {
        Console.WriteLine("The store contains:");
        foreach (Employee e in MyStore)
        {
            Console.WriteLine(e.Position());
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Employee e1 = new Employee("A", 2);
        Employee e2 = new Employee("B", 5);
        Employee e3 = new Employee("J", 7);
        EmpList<Employee> myEmployeeStore = new EmpList<Employee>();
        myEmployeeStore.AddToStore(e1);
        myEmployeeStore.AddToStore(e2);
        myEmployeeStore.AddToStore(e3);

        //Display the Employee Positions in Store
        myEmployeeStore.DisplaySore();
    }
}

Result

The contextual keyword 'where' helps us to place constraints in our application.

In general, we can have the following constraints:

ConstraintMeaning
where T: struct type T must be a value type.
where T: class type T must be a reference type.
where T: IMyInter type T must implement the IMyInter interface.
where T: new() type T must have a default (parameterless) constructor.
where T: S type T must be derived from another generic type S. It is referred to as naked type constraint.

Related Topic