Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a generic class that implements an interface and constrains the type parameter?

class Sample<T> : IDisposable // case A {     public void Dispose()     {         throw new NotImplementedException();     } }  class SampleB<T> where T : IDisposable // case B { }  class SampleC<T> : IDisposable, T : IDisposable // case C {     public void Dispose()     {         throw new NotImplementedException();     } } 

Case C is the combination of case A and case B. Is that possible? How to make case C right?

like image 292
q0987 Avatar asked Jun 03 '11 04:06

q0987


People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

How do you define a generic class?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

How do you declare a generic interface?

Declaring Variant Generic Interfaces You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.


1 Answers

First the implemented interfaces, then the generic type constraints separated by where:

class SampleC<T> : IDisposable where T : IDisposable // case C {        //                      ↑     public void Dispose()     {         throw new NotImplementedException();     } } 
like image 122
dtb Avatar answered Sep 22 '22 07:09

dtb