Should you declare methods using overloads or optional parameters in C# 4.0?

I'd consider the following:

  • Do you need your code to be used from languages which don't support optional parameters? If so, consider including the overloads.
  • Do you have any members on your team who violently oppose optional parameters? (Sometimes it's easier to live with a decision you don't like than to argue the case.)
  • Are you confident that your defaults won't change between builds of your code, or if they might, will your callers be okay with that?

I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to const fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.


When a method overload normally performs the same thing with a different number of arguments then defaults will be used.

When a method overload performs a function differently based on its parameters then overloading will continue to be used.

I used optional back in my VB6 days and have since missed it, it will reduce a lot of XML comment duplication in C#.


I've been using Delphi with optional parameters forever. I've switched to using overloads instead.

Because when you go to create more overloads, you'll invariably conflict with an optional parameter form, and then you'll have to convert them to non-optional anyway.

And I like the notion that there's generally one super method, and the rest are simpler wrappers around that one.


I will definitely be using the optional parameters feature of 4.0. It gets rid of the ridiculous ...

public void M1( string foo, string bar )
{
   // do that thang
}

public void M1( string foo )
{
  M1( foo, "bar default" ); // I have always hated this line of code specifically
}

... and puts the values right where the caller can see them ...

public void M1( string foo, string bar = "bar default" )
{
   // do that thang
}

Much more simple and much less error prone. I've actually seen this as a bug in the overload case ...

public void M1( string foo )
{
   M2( foo, "bar default" );  // oops!  I meant M1!
}

I have not played with the 4.0 complier yet, but I would not be shocked to learn that the complier simply emits the overloads for you.