When I read Scott Guthrie on default parameters I remembered a test I wrote a little while back:

confused

interface IA
{
    void F(int i = 3);
}

class A : IA
{
    public virtual void F(int i = 4)
    {
        Console.WriteLine("Impl A: "+i);
    }
}

class B : A
{
    public override void F(int i = 5)
    {
        Console.WriteLine("Impl B: " + i);
    }
}

class Program
{
    static void Main(string[] args)
    {
        IA ia = new B();
        ia.F();
        A a = new B();
        a.F();
        B b = new B();
        b.F();
    }
}

What is the output? Do you still like default?

It is easy to understand what is going on when you know that defaults are solved at compile time and the default value is hard coded/copied into the method call. At compile time there is no knowledge of run time types…

This entry was posted in Various by Erno de Weerd. Bookmark the permalink.
Erno de Weerd

About Erno de Weerd

Erno de Weerd is oud-medewerker van Info Support. Zijn blogposts zijn dan ook gesloten voor comments.

3 thoughts on “Default, but what default?

  1. Default parameters is a cool feature, but it’s meant for COM interop. An entirely different scenario than what you’re doing here ;)

  2. I know that this feature is very cool for COM interop but it is a language feature that can save you a lot of redundant typing of overloaded versions of a method. And I was just being curious.

  3. They are meant for COM interop, but that doesn’t mean that people won’t use them as an alternative for overloads. It’s good to point out the tricky parts of default parameters, so that people will only use them as they are intended to be used.