Enter your email address:


feedburner count

C# 2.0 : Constraints in Generics

Labels:

Problem

public class Dictionary<K, V>
{
public void Add(K key, V value)
{
...
if (key.CompareTo(x) < 0) {...} // Error, no CompareTo method
...
}
}

Since the type argument specified for K could be any type, the
only members that support CompareTo are memberss that implement
IComparable Interface such as Equals, GetHashCode, ToString...
A Compile-time error occurs in the example above.

Solution

public class Dictionary<K, V> where K: ICompareable
{
public void Add(K key, V value)
{
...
if (key.CompareTo(x) < 0) {...}
...
}
}

The Declaration above ensure that any type argument supplied for K
is a type that implements IComparable. It is possible to specify
any number of interface and type parameters as constraints :

public class Dictionary<K, V>
where K: ICompareable
<K>, IPersistable
where V: Entity
{
public void Add(K key, V value)
{
...
if (key.CompareTo(x) < 0) {...}
...
}
}





blog comments powered by Disqus