C# Program For Default Arguments
C# allows function arguments to have default values such types of arguments known as default arguments. Or in other words, a default argument is an argument whose value is given in the method declaration that will automatically be assigned if the value for the argument is not specified during the function call then the argument will be assigned with a default value. The default value is assigned to the argument with the help of an assignment(=) operator for example “argumentname=value”.
- The value of the default arguments must be constant.
- It can be used with methods, constructors, delegates, etc.
- One should be careful when using default arguments along with method overloading because the compiler might throw an error if there is an ambiguity between default arguments and the overloaded method.
- Once the default value is used for an argument in the function definition, all following arguments should also have a default value else it will throw an error. The following method definition is not valid.
public void methodName(res1, res2 = defaultValue, res3)
This is not the correct function definition because the default arguments should not be followed by normal arguments.
public void methodName(name1, name2, name3 = defaultValue, name4 = defaultValue)
1. Create a method, for example, mydisplay(). Now, in the method definition, take 4 arguments and 3rd and 4th arguments are assigned with default values with the help of the assignment operator (=).
static void mydisplay(int xx, int yy, int zz = 10, int aa = 4)
2. Now, from the main method call the mydisplay() method with a various number of arguments. For example:
mydisplay(200, 456), mydisplay(400, 300, 4562), mydisplay(450, 230, 6070, 234)
3. The mydisplay() method displays the values of the arguments with the help of Console.WriteLine() method.
The value of xx = 200,The value of yy = 456,The value of zz = 10,The value of aa = 4 The value of xx = 400,The value of yy = 300,The value of zz = 4562,The value of aa = 4 The value of xx = 450,The value of yy = 230,The value of zz = 6070,The value of aa = 234
Explanation: In the above example, we created a method named mydisplay with four arguments in which two are normal and two are default arguments. Now, in the mydisplay() method, when called by passing two arguments (i.e xx and yy) the zz and aa will be assigned with default values, and the passed value will be assigned to xx and yy. In a similar fashion when xx, yy, and zz are passed to function the aa will be assigned with the default value, and xx, yy, and zz will be assigned with the assigned values.