method overloading vs optional parameter in C# 4.0

Viewed 80501

which one is better? at a glance optional parameter seems better (less code, less XML documentation, etc), but why do most MSDN library classes use overloading instead of optional parameters?

Is there any special thing you have to take note when you choose to use optional parameter (or overloading)?

11 Answers

This is not really an answer to the original question, but rather a comment on @NileshGule's answer, but:

a) I don't have enough reputation points to comment

b) Multiple lines of code is quite hard to read in comments

Nilesh Gule wrote:

One benefit of using optional parameters is that you need not have to do a conditional check in your methods like if a string was null or empty if one of the input parameter was a string. As there would be a default value assigned to the optional parameter, the defensive coding will be reduced to a great extent.

This is actually incorrect, you still have to check for nulls:

void DoSomething(string value = "") // Unfortunately string.Empty is not a compile-time constant and cannot be used as default value
{
  if(value == null)
    throw new ArgumentNullException();
}

DoSomething(); // OK, will use default value of ""
DoSomething(null); // Will throw

If you supply a null string reference, it will not be replaced by the default value. So you still need to check the input parameters for nulls.

Related