Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface declaration together with generic constraints

Tags:

c#

generics

Basic C# syntax question:

So I have this class

public class BrandQuery<T> : Query<T> where T : Ad
{
  //...
}

How do I specify that BrandQuery implements an interface, say IDisposable ?

This is obviously the wrong way:

public class BrandQuery<T> : Query<T> where T : Ad, IDisposable
{
  //...
}

because that would only put a generic constraint on T.

like image 975
BjartN Avatar asked Aug 09 '09 08:08

BjartN


People also ask

How do you declare a generic interface?

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.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

Can a generic implement an interface?

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

What does the generic constraint of type interface do in C#?

Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type. They declare capabilities that the type argument must have, and must be placed after any declared base class or implemented interfaces.


1 Answers

The generic type constraints follow all the base-class / interfaces:

public class BrandQuery<T> : Query<T>, IDisposable
    where T : Ad
{
  //...
}
like image 129
Marc Gravell Avatar answered Oct 23 '22 11:10

Marc Gravell