You can also set up constraints on generic classes. What if you wanted to create a generic list of objects that derived from a certain base class? This would allow you call certain functions that existed in that class.
By constraining the type, you increase the number of functions you can perform on the type.
// File: Constraints.csusing System;
public class Employee{ private string name; private int id;
public Employee(string name, int id) { this.name = name; this.id = id; }
public string Name { get { return name; } set { name = value; } } public int Id { get { return id; } set { id = value; } }
}
class MyList<T> where T : Employee{ T[] list; int count; public MyList() { list = new T[10]; count = 0; }
public void InsertSorted(T t) { int index = 0; bool added = false;
while (index < count) { if (list[index].Id > t.Id) { for (int last = count; last > index; last--) { list[last] = list[last - 1]; } list[index] = t; added = true; break; } index++; }
if (!added) { list[index] = t; } count++; }}
class Program{ static void Main() { MyList<Employee> myList = new MyList<Employee>();
myList.InsertSorted(new Employee("dan", 200)); myList.InsertSorted(new Employee("sabet", 100)); myList.InsertSorted(new Employee("mike", 150)); myList.InsertSorted(new Employee("richard", 120)); }}