6

I was going through some presentation regarding C# 4.0 and in the end the presenter posted 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 couldn't figure out why that output is produced (problem of reading the presentation offline without the presenter). I was expecting

D x:0, y:1

I searched the net to find the answer but still couldn't find it. Can some one explain this?

ferosekhanj
  • 1,086
  • 6
  • 11
  • This has nothing to do with named parameters. Learn what polymorphism is. – the_drow Jun 10 '11 at 14:40
  • The problem is any developer would expect Derived.Foo to be called due to polymorphism. So it is normal for someone to think that the named parameters in the Derived.Foo will be taken. But since this is runtime polymorphism compiler uses the parameter names from the Base.Foo. – ferosekhanj Jun 13 '11 at 06:15

1 Answers1

3

The reason seems to be the following: You are calling Foo on Base, so it takes the parameter names from Base.Foo. Because x is the first parameter and y is the second parameter, this order will be used when passing the values to the overriden method.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443