0

Is there a way to build an interface like IEnumerable and IEnumerable<T>

public interface IFoo {
    object Bar { get; }
}

public interface IFoo<T> : IFoo {
    T Bar { get; }
}

public class Test : IFoo<int> {
    public new int Bar => 1;
}

this throw an error:

Error: (9.21): Error CS0738: 'Test' does not implement interface member 'IFoo.Bar'. 'Test.Bar' cannot implement 'IFoo.Bar' because it does not have the matching return type of 'object'.

Trejos07
  • 13
  • 3

1 Answers1

1

When implementing an interface your method-signature has to match exactly. Tsimply does not match object. In particular a struct is not an object. So your class has to implement both the generic and the un-generic interface:

So just do this:

public interface IFoo {
    object Bar { get; }
}

public interface IFoo<T> : IFoo {
    T Bar { get; }
}

public class Test : IFoo<int> {
    public int Bar => 1;  // implementation for the generic interface
    object IFoo.Bar => (object) Bar; // explicit implementation for the un-generic interface
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 1
    that is not entirely true anymore see: [C# 9.0 Covariant returns](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/covariant-returns) – Patrick Beynio May 11 '22 at 17:00