Wednesday, July 29, 2009

C# Constraints on Generic Types

C# Constraints on Generic Types

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified by using the where contextual keyword.

Why Use Generic Constraints

If you want to examine an item in a generic list to determine whether it is valid or to compare it to some other item, the compiler must have some guarantee that the operator or method it has to call will be supported by any type argument that might be specified by client code. This guarantee is obtained by applying one or more constraints to your generic class definition. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class. Constraints are applied by using the contextual keyword where.

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 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 myList = new MyList();
myList.InsertSorted(new Employee("dan", 200));
myList.InsertSorted(new Employee("sabet", 100));
myList.InsertSorted(new Employee("mike", 150));
myList.InsertSorted(new Employee("richard", 120));
}
}

No comments:

Post a Comment

Locations of visitors to this page