When I explained functions and methods parameters, I said that we can use them to send different values that our methods and functions can use in their calculations. You should also know that methods and functions can have optional parameters, parameters with a default value, which can be skipped when calling a method or function.
The way we declare a method or function with optional parameters is to specify a default value in the declaration of those parameters, like this:
1 2 3 4 |
static void SomeMethod(int x, int y, int z = 0) { //some code } |
In the above code, because we only declared, but not initialized method parameters x and y, they are mandatory. We cannot call SomeMethod(), without providing values for x and y. However, because we also initialized z as 0, this in turn will make it an optional parameter, which can be skipped when invoking SomeMethod(). The following calls are both valid:
1 2 3 4 5 6 7 8 9 10 11 |
static void Main(string[] args) { SomeMethod(3, 7); //call SomeMethod with only the mandatory parameters SomeMethod(4, 9, 2); //call SomeMethod with all parameters, including optional ones Console.Read(); } static void SomeMethod(int x, int y, int z = 0) { //some code } |
In case we don’t provide a value to the optional parameters when we call the method, if and when we use them in our method, the program will use the default value with which they were initialized in the method or function declaration.
The concepts explained in this lesson are also shown visually as part of the following video:
Tags: functions, functions parameters, methods, methods parameters, optional parameters