Generic type parameter constraints

We can add constraints to generic type parameters with the following syntax.


where: constraint

The constraints can be the follows:

ConstraintMeaning
where T : base-classBase class constraint
where T : interfaceInterface constraint
where T : classReference-type constraint
where T : structValue-type constraint
where T : new()Parameterless constructor constraint
where U : TNaked type constraint
 
using System;

class Shape{

}

class Rectangle: Shape{

}

class Circle: Shape{

}

class GenericClass<T> where T : Shape{

}

class Test
{
    static void Main()
    {
        GenericClass<Rectangle> g = new GenericClass<Rectangle>();
    }
}
  

interface constraint

 
using System;


interface PrintTable{
   void print();
}

class Rectangle : PrintTable
{
}

class GenericClass<T> where T : PrintTable
{
}

class Test
{
    static void Main()
    {
        GenericClass<Rectangle> g = new GenericClass<Rectangle>();
    }
}
  
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.