- - By Craig Buckler

How to Use Optional Parameters in C# 4.0

Optional parameters are default values used when a function or method is called without specific arguments. They can be used in PHP…


// PHP optional parameters
function DoSomething($num = 1, $str = "optional")
{
	// code
}

as well as VisualBasic.NET:


' VB.NET optional parameters
Public Sub DoSomething(
	Optional ByVal num As Integer = 1, 
	Optional ByVal str As String = "optional"
	) 

	' code
	
End Sub

and similar functionality can be written in JavaScript:


// JavaScript optional parameters
function DoSomething(num, str)
{
	num = (typeof(num) != "undefined" ? num : 1);
	str = (typeof(str) != "undefined" ? str : "optional");

	// code
}

In all cases, calling DoSomething without parameters forces num to be 1 and str to be “optional”. Calling DoSomething with a single parameter will set num, but force str to be “optional”. Calling DoSomething with both parameters overrides your defaults.

Although they can be useful, optional parameters were not implemented in C# until version 4.0. If you’ve recently upgraded, you can now write code such as:


// C# optional parameters
void DoSomething(int num = 1, string str = "optional")
{
	// code
}

Those using earlier versions of C# can still implement optional parameter-like code, but it’s achieved with overloading, e.g.


// no parameters
void DoSomething()
{
	int num = 1;
	string str = "optional";

	// code
}
// 
// one parameter
void DoSomething(int num)
{
	string str = "optional";

	// code
}
// 
// two parameters
void DoSomething(int num, string str)
{
	// code
}

Overloading can provide a little more control, but it’s a lot more code for an overworked developer to write!

Sponsors
Login or Create Account to Comment
Login Create Account