C# 4.0 has added two very useful features called Optional Parameters and Named Parameters. For years C# coders have had to settle for overloading their methods to account for parameters that will not always be used.
Optional Parameters Explained
private string YourMethod(string firstName, string lastName = "Doe", int age = 20) { return firstName + " " + lastName; }
In the code above the only required parameter is the first parameter, firstName. The second and third parameters are optional. Below are three different ways you can call this one single method:
string name = null; name = YourMethod("John");
string name = null; name = YourMethod("John","Smith");
string name = null; name = YourMethod("John","Smith",30);
After looking at the above examples you may be wondering, what do I do if I want to pass just the first and third parameters, skipping the second? That is where Named Parameters come in:
Named Parameters Explained
string name = null; name = YourMethod("John", age: 40);
As you can see in the above example, we are able to pass the age parameter by using the new Named Parameters feature.
Popularity: 27%



Write a Comment