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.cs
using 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));
}
}
| Constraint | Description |
| where T: struct | The type argument must be a value type |
| where T: class | The type argument must be a reference type |
| where T: new( ) | The type argument must have a public default constructor |
| where T: <base class name> | The type argument must be the base class name or derived from the base class name. |
| where T: <interface name> | The type argument must be the interface or implement the interface. Multiple interfaces may be specified. |