Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple where for generic type

Tags:

c#

.net

generics

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?

like image 352
Charlie Avatar asked Jun 11 '09 10:06

Charlie


People also ask

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.

Where is generic type constraint?

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.


2 Answers

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
{
}
like image 157
Joshcodes Avatar answered Oct 13 '22 18:10

Joshcodes


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
{
}
like image 38
Jon Skeet Avatar answered Oct 13 '22 17:10

Jon Skeet