9

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)

3 Answers 3

8

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I was going for this: public static List<T> interfacelist = new List<T>; public static void Add(S input); And yeah, it will work too if T is just a base class but the client should be getting interfaces, not base classes.
Here is one (probably edge case) scenario where I would use where T : interface. In unity, there is a method TryGetComponent<T>(), where T is just an object, but when calling it, you get an error that > TryGetComponent should be called only with Types that extend UnityEngine.Component, or Types that are an Interface So I need to specify one option for where T:UnityEngine.Component and second for any interface. Which is not possible at the moment
3
where T: IMyOtherInterfaceForT

Example:

    public class Test<T, V>
    where T : V
    where V : IEnumerable<int>
    {
    }

Comments

2

You could do something like this to enforce it at runtime instead of compile time.

public class Test<T> where T : class
{
  public Test()
  {
    Type t = typeof( T );
    if( !t.IsInterface )
      throw new ArgumentException( "T must be an interface type" );
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.