the WHERE clause in C # 2011-07-03 13:07orphousv | Category: C#/.net | browse 8,443 times
Can you explain the role of where in the following two paragraphs of code?
Using System;
public class MyGenericClass <T> where t:icomparable, new ()
{
The following line was not possible without new () constraint:
T item = new T ();
}
Using System;
Using System.Collections;
Interface MyI
{
}
Class dictionary<tkey,tval>
where tkey:icomparable, IEnumerable
where tval:myi
{
public void Add (TKey key, Tval val)
{
}
}
In addition, what is the actual significance of this feature? How to apply? I would like to cite an example.
Share to:
The WHERE clause of a generic class definition represents a generic type constraint, which is a restriction on the conditions that a generic needs to satisfy.
Like what
where t:icomparable, New ()
Note that the generic T must implement the IComparable interface, and must have a public parameterless constructor.
Because generics are likely to be used in generics-related operations, but because they are generics, there is no guarantee that generics will do this, so there is a constraint that ensures that generics meet the requirements at program compile time.
For example, in the MyGenericClass class you write, the T is instantiated: New T (), which requires that T must have a public parameterless constructor, and if there is no generic type constraint in where, there is no guarantee that such instantiation will succeed.
For a more detailed description, refer to:
The WHERE clause in C #