Subscribe

RSS Feed (xml)

Using Multiple Constraints

There can be more than one constraint associated with a parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be class or struct (if present), or the base class (if one is specified). It is illegal to specify both a class or struct constraint and a base class constraint. Next, must come any interface constraints. The new( ) constraint must be last. For example, this is a valid declaration:
class Gen where T : MyClass, IMyInterface, new() { // ...
In this case, T must be replaced by a type argument that inherits MyClass, implements IMyInterface, and has a parameterless constructor.
When using two or more type parameters, you can specify a constraint for each parameter by using a separate where clause. For example:
// Use multiple where clauses.

using System;

// Gen has two type arguments and both have
// a where clause.
class Gen where T : class
                where V : struct {
  T ob1;
  V ob2;

  public Gen(T t, V v) {
    ob1 = t;
    ob2 = v;
  }
}

class MultipleConstraintDemo {
  public static void Main() {
    // This is OK because string is a class and
    // int is a value type.
    Gen obj = new Gen("test", 11);

    // The next line is wrong because bool is not
    // a reference type.
//    Gen obj = new Gen(true, 11);

  }
}
In this example, Gen takes two type arguments, and both have a where clause. Pay special attention to its declaration:
class Gen where T : class
                where V : struct {

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail