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 😉

Previous post

This Afternoon in Boise

Next post

Book Review : Beyond Code