Default Interface Methods in C# 8
Yes, it is bacause of the new
keyword which actually hides the derived type implementation from parent type as it was exactly the same behavior before too for classes as well which we call Shadowing concept.
So the output would be 55 as you have reference of type IPlayer
for Player
object and ILimitedPlayer
's Attack
method is hidden from IPlayer
because of the new
keyword in it's signatures
I'd say you can get a "good guess" for how this should work without C#8 compiler. What we have here is basically:
public interface IPlayer {
// method 1
int Attack(int amount);
}
public interface IPowerPlayer : IPlayer {
// no methods, only provides implementation
}
public interface ILimitedPlayer : IPlayer {
// method 2, in question also provides implementation
new int Attack(int amount);
}
So we have 2 interface methods (with same signature), and some interfaces (IPowerPlayer
and ILimitedPlayer
) provide implementations of those methods. We can just provide implementaitions in Player
class itself to achieve similar functionality:
public class Player : IPowerPlayer, ILimitedPlayer {
int IPlayer.Attack(int amount) {
return amount + 50;
}
int ILimitedPlayer.Attack(int amount) {
return amount + 10;
}
}
Then running code from question outputs:
55
55
15
And I think it's relatively clear why.