Matthew Scharley Matthew Scharley - 3 months ago 10
C# Question

How can I use interface as a C# generic type constraint?

Is there a way to get the following function declaration?

public bool Foo<T>() where T : interface;


ie. where T is an interface type (similar to
where T : class
, and
struct
).

Currently I've settled for:

public bool Foo<T>() where T : IBase;


Where IBase is defined as an empty interface that is inherited by all my custom interfaces... Not ideal, but it should work... Why can't you define that a generic type must be an interface?

For what it's worth, I want this because
Foo
is doing reflection where it needs an interface type... I could pass it in as a normal parameter and do the necessary checking in the function itself, but this seemed a lot more typesafe (and I suppose a little more performant, since all the checks are done at compiletime).

Answer

The closest you can do (except for your base-interface approach) is "where T : class", meaning reference-type. There is no syntax to mean "any interface".

This ("where T : class") is used, for example, in WCF to limit clients to service contracts (interfaces).