Named parameters

Named parameters were introduced in C# 4.0, and they allow us to pass arguments to a method/constructor/delegate/indexer using parameter names instead of the sequence in which the parameters are passed. 

Using named parameters, developers no longer need to be concerned about the sequence in which they need to pass parameters. As long as they associate the values being passed with the right parameter name, the sequence will not matter. The parameter names are compared against the names of the parameters in the method definition. Let's look at the following code example to understand how it works:

internal Double CalculateCompoundInterest(Double principle, Double interestRate, int noOfYears)
{
Double simpleInterest = (principle) * Math.Pow((1 +
(interestRate)/100), noOfYears);
return simpleInterest;
}

In the preceding code example, we are calculating compound interest by passing the principal amount, interest rate, and number of years for which the amount was put in the bank. 

If we call the method without using named parameters, we would use the following code snippet:

Double interest = CalculateCompoundInterest(500.5F, 10.5F, 1);            

If we look closely at the preceding example, while calling the function, the developer will need to be fully aware of the sequence of the principle and interest rate parameters. That's because if the developer makes a mistake while calling the function, the resultant output will be incorrect. 

With named parameters, we can call the method using the following syntax:

Double namedInterest = CalculateCompoundInterest(interestRate: 10.5F, noOfYears: 1, principle: 500.5F); 

Note that, in the preceding code, we are not passing values to the parameters in the sequence there are defined in the method. Instead, we are using parameter names to map the passing values with the parameters declared in the method. In the next section, we will look at another feature, optional parameters, which was introduced in C# 4.0 along with named parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.70