Wednesday, 1 December 2010

Defining Optional Parameters for Methods using C# 4.0

The ability to create methods or functions with optional parameters/arguments was there in VB 6.0. How ever it was taken away when .Net came into action. And it was not there in earlier versions. But now it's available again in framework version 4.0.

Assume you have a method called "Greeting" which defines a single optional parameter:

static void Greeting(string message, string user = "Guest") {
Console.WriteLine(message + ", {0}",user);


So when the method is called by passing a value only to the first parameter, the default value of "Guest" will be assigned to the second argument. And you will get the following output.




And when the method is called passing parameters to both arguments, you will get the following output.



No comments:

Post a Comment