Wednesday, June 2, 2010

Code: C# Optional Parameters

One of the new features of C# in .Net 4.0 is optional parameters.  VB has had this language feature for a while, and its nice to see it make its way to C#.  If you don’t like optional parameters you can still use method overloading, but it will definitely be useful in some situations.  To make a parameter optional, you just need to specify what the default value for the parameter is:

public int Add(int firstNumber, int secondNumber = 0, bool isAbsolute = false)
{
int result = firstNumber + secondNumber;

if (isAbsolute)
result = Math.Abs(result);

return result;
}

add