I need to specify that a generic type for my class implements an interface, and is also a reference type. I tried both the code snippets below but neither work
public abstract class MyClass<TMyType>
where TMyType : IMyInterface
where TMyType : class
public abstract class MyClass<TMyType>
where TMyType : class, IMyInterface
I'm unable to specify multiple where clauses for a type, is it possible to do this?
A Generic class can have muliple type parameters.
Multiple interface constraints can be specified. The constraining interface can also be generic.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
A question about how to define multiple where
clauses links here as a duplicate. If that question truly is a duplicate than this "complete" answer must contain both cases.
Case 1 -- Single generic has multiple constraints:
public interface IFoo {}
public abstract class MyClass<T>
where T : class, IFoo
{
}
Case 2 -- Multiple generics each with their own constraints:
public interface IFoo1 {}
public interface IFoo2 {}
public abstract class MyClass<T1, T2>
where T1 : class, IFoo1
where T2 : IFoo2
{
}
The latter syntax should be fine (and compiles for me). The first doesn't work because you're trying to provide two constraints on the same type parameter, not on different type parameters.
Please give a short but complete example of the latter syntax not working for you. This works for me:
public interface IFoo {}
public abstract class MyClass<T>
where T : class, IFoo
{
}
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