Optional parameter is the feature of c# 4.0
Named and optional parameters are really two distinct features, and allow us to either omit parameters which have a defined default value, and/or to pass parameters by name rather than position. Named parameters are passed by name instead of relying on its position in the parameter list, whereas optional parameters allow us to omit arguments to members without having to define a specific overload matching.
Let’s have a look at Optional parameters:
//In old way we will write the code as shown below.
public static double MyOldCurrencyExchange(double amount, double rate)
{
return (amount * rate);
}
We will call the above method as shown below:
MyOldCurrencyExchange(500, 1.18);
Now, by using Optional parameters:
//In new way we will write the code as shown below
public static double MyNewCurrencyExchange(double amount, double rate=1)
{
return (amount * rate);
}
We will call the above method as shown below:
MyNewCurrencyExchange (500, 1.18); // ordinary call
MyNewCurrencyExchange (500); // omitting rate
Now, by using Named parameters:
MyNewCurrencyExchange (rate:1.18, amount:500); // reversing the order of arguments.
Now, by using Named and Optional parameters:
MyNewCurrencyExchange (amount:500);
another example :
using System;
class Program
{
static void Main()
{
// Omit the optional parameters.
Method();
// Omit second optional parameter.
Method(4);
// You can't omit the first but keep the second.
// Method("Vamsi");
// Classic calling syntax.
Method(4, "Vamsi");
// Specify one named parameter.
Method(name: "Vamsi Krishna");
// Specify both named parameters.
Method(value: 5, name: "Reddy");
}
static void Method(int value = 1, string name = "Perl")
{
Console.WriteLine("value = {0}, name = {1}", value, name);
}
}
Output
value = 1, name = Perl
value = 4, name = Vamsi
value = 4, name = Vamsi
value = 1, name = Vamsi Krishna
value = 5, name = Reddy
No comments:
Post a Comment