C# Multiple constraints

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2010-05-20T14:44:31Z Indexed on 2010/05/20 14:50 UTC
Read the original article Hit count: 230

Filed under:
|

I have an application with lots of generics and IoC. I have an interface like this:

public interface IRepository<TType, TKeyType> : IRepo

Then I have a bunch of tests for my different implementations of IRepository. Many of the objects have dependencies on other objects so for the purpose of testing I want to just grab one that is valid. I can define a separate method for each of them:

public static EmailType GetEmailType()
{
  return ContainerManager.Container.Resolve<IEmailTypeRepository>().GetList().FirstOrDefault();
}

But I want to make this generic so it can by used to get any object from the repository it works with. I defined this:

public static R GetItem<T, R>() where T : IRepository<R, int>
{
  return ContainerManager.Container.Resolve<T>().GetList().FirstOrDefault();
}

This works fine for the implementations that use an integer for the key. But I also have repositories that use string. So, I do this now:

public static R GetItem<T, R, W>() where T : IRepository<R, W>

This works fine. But I'd like to restrict 'W' to either int or string. Is there a way to do that?

The shortest question is, can I constrain a generic parameter to one of multiple types?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics