C
C#2y ago
SirCarter

❔ Covariant Interface Return

Is there some reason why this doesn't work? I understand we can get this behavior with virtual methods and inheritance, but it feels like this should work with interfaces.
interface IFooReturner { Foo GetFoo(); }
class Foo {}
class FooBar : Foo {}
class FooBarGetter : IFooReturner { FooBar GetFoo(); }
interface IFooReturner { Foo GetFoo(); }
class Foo {}
class FooBar : Foo {}
class FooBarGetter : IFooReturner { FooBar GetFoo(); }
If FooBar is a Foo, this implementation should be valid no?
7 Replies
ero
ero2y ago
no, interfaces are contracts any implementing classes must fulfill them exactly
SirCarter
SirCarterOP2y ago
It kinda does though
ero
ero2y ago
it doesn't FooBar is not Foo
SirCarter
SirCarterOP2y ago
class FooReturner { virtual Foo GetFoo(); }
class Foo {}
class FooBar : Foo {}
class FooBarGetter : FooReturner { override FooBar GetFoo(); }
class FooReturner { virtual Foo GetFoo(); }
class Foo {}
class FooBar : Foo {}
class FooBarGetter : FooReturner { override FooBar GetFoo(); }
So something like this works, we can override the return type and it still works because FooBar is a Foo, it still matches the contract of the original class but with more specificity I'm not sure I'm understanding why they can't do the same things with an interface, if I cass FooBarGetter to IFooReturner, I'd still get a Foo from GetFoo
reflectronic
reflectronic2y ago
the feature is deliberately only implemented for classes the implementation is much more complex for interfaces so they did not do it
SirCarter
SirCarterOP2y ago
Sad but that makes sense
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server