Is it possible to specify default options in C #?
In C:
void fun(int i = 1) { printf("%d", i); }
Can we give the parameters a default value? Is this possible in C #? If so, can we avoid function overloading?
It is always useful to use an optional parameter for an existing function. If you are working on a project that has to refer to a class that has a function, and we changed the parameter with an optional value, it may throw a runtime exception that the method was not found.
This is because we will take into account that if we add an additional optional value, no code change will be required if the function is used in many places.
function Add(int a, int b);
This will be invoked as follows:
Add(10, 10);
But if we add an optional parameter, for example,
function Add(int a, int b, int c = 0);
then the compiler expects
Add(10, 10, 0);
In fact, we call this Add(10, 10) , and this function will not be available in this class and will throw a runtime exception.
This happens by adding a new parameter to the function called by many places, and I'm not sure if this happens every time. But I suggest you overload the function.
You always need to overload a method that has an optional parameter. Also, if you are working with functions that have more than one optional parameter, then it is useful to pass the value using the parameter name.
function Add(int a, int b, int c = 0);
It is always useful to call this function as follows.
Add(10, 20, c:30);