Optional parameters and named parameters in C# 4.0
Feb 9, 2010
Optional parameters and named parameters in C# 4.0
Imagine you have two List
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 = "Kannan",
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("Arjun");
That will return Arjun Kannan. You can also do this:
string name = null;
name = SomeMethod("FName", "LName");
The value returned is FName LName. 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("Rangoli", age: 20);
These are nice additions to the language.
Share