we will discuss the different ways that are available to make method parameters optional. This is a very common interview question.
There are 4 ways that can be used to make method parameters optional.
1. Use parameter arrays
2. Method overloading
3. Specify parameter defaults
4. Use OptionalAttribute that is present in System.Runtime.InteropServices namespace
Using parameter arrays, to make method parameters optional:
AddNumbers function, allows the user to add 2 or more numbers. firstNumber and secondNumber parameters are mandatory, where as restOfTheNumbers parameter is optional.
public static void AddNumbers(int firstNumber, int secondNumber,
params object[] restOfTheNumbers)
{
int result = firstNumber + secondNumber;
foreach (int i in restOfTheNumbers)
{
result += i;
}
Console.WriteLine("Total = " + result.ToString());
}
Please note that, a parameter array must be the last parameter in a formal parameter list. The following function will not compile.
public static void AddNumbers(int firstNumber, params object[] restOfTheNumbers,
int secondNumber)
{
// Function implementation
}
If the user wants to add just 2 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20);
On the other hand, if the user wants to add 5 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20, 30, 40, 50);
or
AddNumbers(10, 20, new object[] { 30, 40, 50 });
There are 4 ways that can be used to make method parameters optional.
1. Use parameter arrays
2. Method overloading
3. Specify parameter defaults
4. Use OptionalAttribute that is present in System.Runtime.InteropServices namespace
Using parameter arrays, to make method parameters optional:
AddNumbers function, allows the user to add 2 or more numbers. firstNumber and secondNumber parameters are mandatory, where as restOfTheNumbers parameter is optional.
public static void AddNumbers(int firstNumber, int secondNumber,
params object[] restOfTheNumbers)
{
int result = firstNumber + secondNumber;
foreach (int i in restOfTheNumbers)
{
result += i;
}
Console.WriteLine("Total = " + result.ToString());
}
Please note that, a parameter array must be the last parameter in a formal parameter list. The following function will not compile.
public static void AddNumbers(int firstNumber, params object[] restOfTheNumbers,
int secondNumber)
{
// Function implementation
}
If the user wants to add just 2 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20);
On the other hand, if the user wants to add 5 numbers, then he would invoke the method as shown below.
AddNumbers(10, 20, 30, 40, 50);
or
AddNumbers(10, 20, new object[] { 30, 40, 50 });
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.