Graphic details about where type constraints in C #

Source: Internet
Author: User
constraints on type parameters (C # Programming Guide)

Visual Studio 2005





Other versions

When you define a generic class, you can impose restrictions on the type types that client code can use for type parameters when instantiating a class. If the client code attempts to instantiate a class with a type that is not allowed by a constraint, a compile-time error occurs. These restrictions are called constraints. Constraints are specified using the where context keyword. The following table lists the six types of constraints:

Constraints description

T: Structure

t: Class

t:new ()

new () constraint must be specified last.

t:< base class name;

t:< interface name;

t:u

The type parameter provided for T must be either a parameter supplied for u or a parameter derived from U. This is called a bare type constraint.


Reasons for using constraints

If you want to examine an item in the generic list to determine if it is valid, or compare it to one of the other items, the compiler must be certain that the operator or method it needs to invoke will be supported by any type parameter that the client code might specify. This guarantee is obtained by applying one or more constraints to the generic class definition. For example, a base class constraint tells the compiler that only objects of this type or objects derived from this type can be used as type parameters. Once the compiler has this assurance, it is able to allow methods of that type to be called in the generic class. Constraints are applied using the context keyword where . The following code example shows the functionality that can be added to the Genericlist<t> class (In the generic Introduction (C # Programming Guide)) by applying a base class constraint.

public class employee{private string name;    private int id;        Public Employee (string s, int i) {name = S;    id = i;        } public string Name {get {return Name;}    set {name = value;}        } public int ID {get {return id;}    set {id = value;}        }}public class genericlist<t> where t:employee{private class Node {private node Next;        Private T data;            Public Node (T t) {next = null;        data = t;            } public Node Next {get {return next;}        set {next = value;}            } public T Data {get {return Data;}        set {data = value;}    }} private Node head;    Public GenericList ()//constructor {head = null;        } public void AddHead (T t) {node n = new Node (t);        N.next = head;    Head = N;       } public ienumerator<t> GetEnumerator () { Node current = head; while (current = null) {yield return current.            Data; Current = current.        Next;        }} public T findfirstoccurrence (string s) {Node current = head;        T t = null;            while (current = null) {//the constraint enables access to the Name property. if (current. Data.name = = s) {t = current.                Data;            Break } else {current = current.            Next;    }} return t; }}

Constraint type parameters allow you to increase the number of allowable operations and method calls supported by all types in the constraint type and its inheritance hierarchy. Therefore, when designing a generic class or method, if you want to perform any operation other than simple assignment on a generic member or call any method that System.Object does not support, you will need to apply a constraint to that type parameter.

When you apply a where T:class constraint, we recommend that you do not use the = = and! = operators for type parameters, because these operators test only the identity of a reference and do not test for value equality. This is true even if the operators are overloaded with types that are used as parameters. The following code illustrates this; even if the String class overloads the = = operator, the output is false.

C#

public static void Optest<t> (t s, T T) where t:class{    System.Console.WriteLine (s = = t);} static void Main () {    string s1 = "Foo";    System.Text.StringBuilder sb = new System.Text.StringBuilder ("foo");    String s2 = sb. ToString ();    Optest<string> (s1, S2);}

The reason for this is that the compiler only knows that T is a reference type at compile time, so you must use the default operator that is valid for all reference types. If you need to test for value equality, the recommended approach is to apply the where t:icomparable<t> constraint at the same time and implement the interface in any class that will be used to construct the generic class.

Unbound type parameter


Type parameters without constraints, such as T in public class sampleclass<t>{} , are called unbound type parameters. Unbound type parameters have the following rules:

    • You cannot use the! = and = = operators Because these operators are not guaranteed to be supported by a specific type parameter.

    • You can convert back and forth between them and System.Object , or explicitly convert them to any interface type.

    • They can be compared with null. When an unbound parameter is compared to null , the comparison will always return FALSE if the type parameter is a value type.

Bare type constraints


A generic type parameter used as a constraint is called a bare type constraint. A bare type constraint is useful when a member function that has its own type parameter needs to constrain the parameter to a type parameter that contains a type, as shown in the following example:

C#

Class list<t>{    void Add<u> (list<u> items) where U:t {/*...*/}}

In the example above,T is a bare type constraint in the context of the Add method, and is an unbound type parameter in the context of the List class.

Bare-type constraints can also be used in generic class definitions. Note that the bare type constraint must also be declared in angle brackets with any other type parameter:

C#//naked type Constraintpublic class Sampleclass<t, U, v> where t:v {}

The bare type constraints of a generic class are very limited because the compiler does not make any assumptions other than assuming that a bare type constraint derives from System.Object . You can use a bare type constraint on a generic class in cases where you want to enforce an inheritance relationship between two type parameters.

Above is the description of the Where type constraint in C #, and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.