Optional parameters

Optional parameters in C# allow us to define a method in such a way that some of the parameters are optional. In other words, while defining the function for the optional parameters, a default value is specified. 

If, while calling the method, no value is passed for the optional parameter, it assumes a default value. Let's look at a code example to understand how optional parameters work in C#:

static float MultiplyNumbers(int num1, int num2 = 2, float num3 = 0.4f)
{
return num1 * num2 * num3;
}

In the preceding code example, we have defined a MultiplyNumbers method with three parameters, num1, num2, and num3. The num1 parameter is mandatory, while the other two parameters, num2 and num3, are optional.

Please note that, while defining the function, the optional parameters, if any, must come after all of the required parameters have been specified in the sequence.

If we need to execute the preceding method, we can use any of the following code snippets:

float result = MultiplyNumbers(2); // output = 1.6f
float result1 = MultiplyNumbers(2, 5); // output = 4f
float result2 = MultiplyNumbers(2, 4, 5); // output = 40f

Note that there would be no compiler errors and if any optional parameters are not passed, the default value defined in the function declaration would be used. In the next section, we will look at how generic types are implemented in C#.

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

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