Two new features to 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 ConcatanationNameAndSurname(string givenName,
    string surname = "DUBAL", int age = 21)
{
return givenName + " " + surname +" "+ "AGE:"+age;
}

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 = ConcatanationNameAndSurname("KARAN");

That will return "KARAN DUBAL 21". You can also do this:

string name = null;
name = ConcatanationNameAndSurname("ABC", "DEF"); 

The value returned is "ABC DEF 21". 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 = ConcatanationNameAndSurname("KARAN", age: 22);

The value returned is "KARAN 21"

These are nice additions to the language.
Ebook Download
View all
Pristine
Read by 0 people
Download Now!
Learn
View all