Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force generic interface implementation in C#

Is there anyway to force a constraints for a generic definition to implement a "generic interface" ... that is, I want the class to support passing an interface and a generic class constraining it so that the class implements the interface. For example if I say:

MyGenericClass<IMyInterface, MyImplementation>.DoSomething();

That should be constrained so that MyImplementation implements IMyInterface

As far as I know that can be achieved by

public class Dynamic_Loader<T, S> where S: T

Now, is there anyway to also force T to be an interface?

Edit: The purpose of this was to have something like:

private static List<T> interfaceList = new List<T>();

public static List<T> InterfaceList {get { return interfaceList;}}

public static void Add(S input) { interfaceList.Add(input);}

and have the list restricted to only interfaces (since it is supposed to return implementations of certain interfaces)

like image 362
Jorge Córdoba Avatar asked Aug 30 '10 13:08

Jorge Córdoba


People also ask

Can a generic implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

Do generics increase performance?

With using generics, your code will become reusable, type safe (and strongly-typed) and will have a better performance at run-time since, when used properly, there will be zero cost for type casting or boxing/unboxing which in result will not introduce type conversion errors at runtime.

What does the generic constraint of type interface do in C#?

Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type. They declare capabilities that the type argument must have, and must be placed after any declared base class or implemented interfaces.

What is the syntax used to declare generic interface?

The general syntax to declare a generic interface is as follows: interface interface-name<T> { void method-name(T t); // public abstract method. } In the above syntax, <T> is called a generic type parameter that specifies any data type used in the interface.


1 Answers

Do you mean, can a constraint also be put on T like where T : interface?

If so, then no: this list pretty much covers your options.

What you have is as close as it gets, I believe.

Out of curiosity, what would be your reason for wanting to constrain T to be an interface?

Or do you mean can a constraint also be put on T for T to implement some specific interface?

If so, then yes: simply have two where clauses (e.g., where S : T where T : U).

like image 153
Dan Tao Avatar answered Sep 27 '22 20:09

Dan Tao