C# Default Arguments [Optional Arguments]

Monday, September 05, 2011

Coming from the C++ world, one of the things I missed in C# was the support for Default Arguments. Default arguments are used to create functions which could have a few optional arguments with default values. Thus, you could make overloaded calls to the method without creating different function prototypes if the purpose could by using a default value of one of the parameters. Many other common languages like PHP, VB.NET, JavaScript etc. also support this feature. It was surprising that C# did not support it.

With C# 4.0 (2010), the support for this feature has been added to the language. The new Optional Arguments in C# 4.0 allows you to specify the default values of parameters in case there values are not provided from the function call. Here's a small example to illustrate the basics of Optional Arguments in C#:


// Function with optional arguments
void OptionalArgExample(int reqdField, string opt = "default value")
// do something

// Calling the method with just the required argument

// Calling the method with both the arguments
OptionalArgExample(10, "some text");

For more information, read the MSDN article on Named and Optional Arguments in C#


Post a Comment