C # Named Parameters, Inheritance and Overload

I did a presentation on C # 4.0, and at the end the presenter sent a quiz with the following code.

using System; class Base {    public virtual void Foo(int x = 4, int y = 5) {        Console.WriteLine("B x:{0}, y:{1}", x, y);    } } class Derived : Base {    public override void Foo(int y = 4, int x = 5) {        Console.WriteLine("D x:{0}, y:{1}", x, y);    } } class Program {    static void Main(string[] args) {        Base b = new Derived();        b.Foo(y:1,x:0);    } } // The output is // D x:1, y:0 

I could not understand why this conclusion was made (the problem of reading the presentation offline without a presenter). I expected

 D x:0, y:1 

I searched the net to find the answer, but still could not find it. Can someone explain this?

+6
source share
1 answer

The reason is this: you call Foo on Base , so it takes parameter names from Base.Foo . Since x is the first parameter, and y is the second parameter, this order will be used when passing values ​​to the override method.

+3
source

Source: https://habr.com/ru/post/890223/


All Articles