Search This Blog

Wednesday, October 15, 2014

Where keyword generic generic type constraint example C#

C# > Generics > where - generic type constraint

With where keyword you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates the generics class.


Example


    public class A
    {
    }
    public class B:A
    {
    }
    public class GenericList <T> where T : A
    {
    }

    GenericList<A> lst1 = new GenericList<A>(); // OK
    GenericList<B> lst2 = new GenericList<B>(); // OK B derives from A
    GenericList<int> lst3 = new GenericList<int>(); //Error  1      The type 'int' cannot be used as type parameter 'T' in the generic type or method 'WindowsFormsApplication1.GenericList'. There is no boxing conversion from 'int' to 'WindowsFormsApplication1.A'.