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.
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.
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.
Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.
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.
The generic type constraints follow all the base-class / interfaces:
public class BrandQuery<T> : Query<T>, IDisposable
where T : Ad
{
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With