Monday, August 17, 2009

Two New Features of C# 4.0

Two new features to C# 4.0 are optional parameters and named parameters. Optional parameters have been a part of VB.Net but it's now possible to do this in C#. Instead of using overload methods, you can do this in C#:

private string SomeMethod(string givenName,
string surname = "Sheridan", int age = 10)
{
return givenName + " " + surname;
}

The second and third parameters, surname & age, both have default values. The only parameter required is givenName. To call this method you can either write this:

string name = null;
name = SomeMethod("Malcolm");

That will return Malcolm Sheridan. You can also do this:

string name = null;
name = SomeMethod("Suprotim", "Agarwal");

The value returned is Suprotim Agarwal. But what if you didn't want to specify a surname but you did want to pass the age? You can do this by using named parameters:

string name = null;
name = SomeMethod("Suprotim", age: 20);

These are nice additions to the language.

No comments:

Post a Comment