0

I'm trying to create a method that through generics tries to pass an interface and a class. It should look something like this, but this does not build:

public static void Register<TInterface, TClass>() 
  where TClass     : TInterface 
  where TInterface : interface // <- doesn't compile
{
   ...
}

Is there any way to get this to work. The idea is to build a wrapper around an ioc container.

5
  • 1
    There is not where T : interface constraint in c#, you can use only interface name. You can use something like that where TClass : class, TInterface Commented Feb 4, 2020 at 10:29
  • Why do you want to put constraint : interface? What's wrong if I provide, say, abstract class for TInterface? Commented Feb 4, 2020 at 10:29
  • 2
    No. You can't constrain type parameters to interfaces. In general, if you find your generics wanting to impose constraints like this, it's typically a sign you've gone too far, as there's not much meaningful you can do with the knowledge. It's just "lining up types nicely" for appearances' sake. Commented Feb 4, 2020 at 10:30
  • This looks like you're implementing a sort of "poor man's dependency injection". Take a look at how other mature container implementations do it, they will have something like void Register<TService, TImplementation>() where TService: class where TImplementation : class, TService Commented Feb 4, 2020 at 10:36
  • There is similar kind of question in stack overflow as stackoverflow.com/questions/1104229/… Commented Feb 4, 2020 at 10:52

1 Answer 1

1

You cannot do it the way you want. The closest you will be able to achieve is by limiting TClass to inherit/implement the TInterface, but TInterface can also be a class (and TClass can also be an interface. Perhaps its worth noting that class does not mean class but any reference type. It can also be an interface)

public static void Register<TInterface, TClass>() 
  where TClass     : class, TInterface
  where TInterface : class
{

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

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.