Friday, 23 August 2013

Define a class MyClass or a function MyFunction(T x) where T can only by a type that implements IMyInterface

Define a class MyClass or a function MyFunction(T x) where T can only by a
type that implements IMyInterface

I want to define a class MyClass<T> and a very particular function
MyFunc<T>, but I want to force T to inherit from (in any way) an interface
or a class. Let's call this IMyInterface.
The only way my knowledge of C# allows me to do this is to define a
generic class, check if it inherits (see In C#, how do I check if a type
is a subtype OR the type of an object? for example), and throw an
exception otherwise.
Is there a way to force this at compile-time, rather than runtime?

No comments:

Post a Comment