Wednesday 1 December 2010

Calling Methods using Named Parameters using C# 4.0

Another new feature added to .Net 4.0 is to call methods using named parameters. This is very handy when calling a method which has optional arguments (You can use this to call other methods which consist of non optional parameters too). We’ll consider the following method.

static void SampleMethod(string ar1, 
string ar2 = "",
string ar3 = "",
string ar4 = "",
string ar5 = "",
string ar6 = "") {



//Some logic..
Console.WriteLine(ar6);
}



And assume that we only need to pass a value only to the last parameter. If the named parameter method was not there, the way to call the method would be something like this:


SampleMethod("message", "", "", "", "", "Hello World!");



But instead we can call the method using the following syntax.


SampleMethod(
ar1: "message",
ar6: "Hello World!");



And you will get the following output:


screen_1

No comments:

Post a Comment