Wednesday, April 25, 2012

New features of C# 4.0-Named and Optional Parameters

The new release of Visual Studio.NET 2010 and Microsoft.NET Framework 4.0, we have new features added to the C# language. The new features being integrated with the new version of the language C# 4.0.

Here is a list of new features added to C# 4.0.

•Dynamic programming

•Named and optional parameters

•Covariance and Contravariance
 
Named and Optional Parameters



Another new feature is named and optional parameters. Optional parameters allow giving a method parameter a default value, so you don't have to specify it every time you call the method (see Listing 3).


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace CSharpNewFeatures

{

class Program

{

public static void Method(int age, String firstname="Vijayanand", double salary=60000.99)

{ }

static void Main(string[] args)

{

Method(30); //The same as Method(30,"Vijayanand",60000.99)

Method(30, "Vijayanand"); //The same as Method(30,"Vijayanand",60000.99)

Method(30, "Vijayanand", 60000.99);

}

}

}



Using named parameter, a developer can skip parameters that have default values, and name only the parameters that have non-default values.

For example if you write the following code , you will get an error because the second parameter's type, in the method invocation, does not match with a String data type.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace CSharpNewFeatures

{

class Program

{

public static void Method(int age, String firstname="Vijayanand", double salary=60000.99)

{ }

static void Main(string[] args)

{

Method(30, 60000.99);

}

}

}

In order to solve this problem, we're going to use named parameters as shown below. You can see that the syntax is very simple. Just call the parameters by [parameter_name]:[parameter_value].

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace CSharpNewFeatures

{

class Program

{

public static void Method(int age, String firstname="Vijayanand", double salary=60000.99)

{ }

static void Main(string[] args)

{

Method(30, salary:60000.99);

}

}

}

Happy Coding ..............

0 comments:

Popular Posts

Recent Posts

Unordered List

Text Widget