'C# implement generic interface like IEnumerable and IEnumerable<T> [duplicate]
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'.
Solution 1:[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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MakePeaceGreatAgain |
