Search code examples
c#genericsinterfaceconstraintsexplicit-interface

Type parameter 'T' has the same name as the type parameter from outer type '...'


public abstract class EntityBase { ... }

public interface IFoobar
{
    void Foo<T>(int x)
        where T : EntityBase, new();
}

public interface IFoobar<T>
    where T : EntityBase, new()
{
    void Foo(int x);
}

public class Foobar<T> : IFoobar, IFoobar<T>
    where T : EntityBase, new()
{
    public void Foo(int x) { ... }

    void IFoobar.Foo<T>(int x) { Foo(x); }
}

I get a compiler warning: Type parameter 'T' has the same name as the type parameter from outer type '...'

I tried doing: void IFoobar.Foo<U>(int x) { Foo(x); }, however then I can't guarantee that U and T are the same. The way that the Foobar class is implemented, it is very important that they be the same.

I also tried doing: void IFoobar.Foo<U>(int x) where U : T { Foo(x); }, however that does not guarantee that U and T are equal and it does not allow me to redefine the constraint since it was defined on the interface.


Solution

  • You can do one of two things:

    1. Ignore the warning and make both types T.
    2. Do a run-time check and throw an exception:

      if (typeof(T) != typeof(U)) throw Exception("Not the same type");
      

    As others have stated, perhaps you need to rethink the way you are designing your interfaces.