Blog

  • Home /
  • Blog /
  • Be careful with optional parameters in C# 4.0

Be careful with optional parameters in C# 4.0

November 9, 2008

I've been playing with the Visual Studio 2010 CTP bits, and I tried to see what named and optional parameters in C# 4.0 can bring to the table. Although they are minor language enhancements at best, they can cause a lot of grief as well.

In my former life as a C++ developer, optional parameters were quite handy in some cases to remove some ceremonial code for providing obvious overloads of a method. Since I came over to the .NET platform, I actually don't miss optional parameters. I just wanted to share a common abuse of optional parameters that you should be aware of. The following code illustrates this:

public class Base
{
    public virtual void Foo(Int32 x = 1) 
    {}   
}

public class Derived
{
    public override void Foo(Int32 x = 2)
    {}
}

...

Base f0 = new Base();
f0.Foo();                // Invokes Foo(1)

Base f1 = new Derived();
f1.Foo();               // Also invokes Foo(1)

Derived f2 = new Derived();
f2.Foo();               // Invokes Foo(2)

This is something you have to watch out for. The object's member function silently takes different arguments depending on the static type you use. This violates the principle of least surprise and is a general PITA. Don't violate the method contract that has been provided by the base class.

Don't say I didn't warn you ;-)

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be