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)?
One good use case for ‘Optional parameters’ in conjunction with ‘Named Parameters’ in C# 4.0 is that it presents us with an elegant alternative to method overloading where you overload method based on the number of parameters.
For example say you want a method
footo be be called/used like so,foo(),foo(1),foo(1,2),foo(1,2, "hello"). With method overloading you would implement the solution like this,With optional parameters in C# 4.0 you would implement the use case like the following,
Then you could use the method like so – Note the use of named parameter –
This call takes parameter
avalue as 10 and parameterbas 23.Another variant of this call – notice you don’t need to set the parameter values in the order as they appear in the method signature, the named parameter makes the value explicit.
Another benefit of using named parameter is that it greatly enhances readability and thus code maintenance of optional parameter methods.
Note how one method pretty much makes redundant having to define 3 or more methods in method overloading. This I have found is a good use case for using optional parameter in conjunction with named parameters.