Wednesday, May 25, 2011

Optional Parameters

.NET 4.0 added the often requested ability to specify a default value for a parameter making it optional for callers. The optional parameters have to be at the end of the parameter values and must be constants.
Generally they should be used where you would have created an overloaded method just to pass in a default value for one or two parameters. Don’t use them in place of good object initialization code or for every parameter a function takes.
For example the following overloaded methods:
/// <summary>
/// Return the contents of the text node associated with the passed element.
/// Return the empty string if there is no text node.
/// </summary>
public static string GetText(XmlElement element) {
     return GetText(element, string.Empty);
}


/// <summary>
/// Return the contents of the text node associated with the passed element.
/// Return the default value if there is no text node.
/// </summary>
public static string GetText(XmlElement element, string defaultValue) {

Can be simplified into one method by making the second parameter optional:
/// <summary>
/// Return the contents of the text node associated with the passed element.
/// Return the default value if there is no text node 
/// or empty string if not specified.
/// </summary>
public static string GetText(XmlElement element, string defaultValue = "") {

Note while you can use constants like int.MinValue and long.MaxValue, string.Empty is a field on the String class and cannot be specified. You have to use "" for empty strings.

No comments: