The WHERE clause in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.