Charlie
Charlie

Reputation: 10307

Multiple where for generic type

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?

Upvotes: 12

Views: 16489

Answers (2)

Joshcodes
Joshcodes

Reputation: 8871

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
{
}

Upvotes: 22

Jon Skeet
Jon Skeet

Reputation: 1500675

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
{
}

Upvotes: 9

Related Questions