Showing posts with label New Features Of .Net 4.0. Show all posts
Showing posts with label New Features Of .Net 4.0. Show all posts

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

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.


Greeting("Hello");

screen_1

 


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


Greeting("Hello","John");

screen_2