is it possible to do this in C#? (in C++ its not)
function sum ( int a = 9, int b = 4){
}
and then call the function like :
int someValue = sum(, 14) // so 14 is for the second value
For instance, if a bank's interest rate for the current financial year is 8 percent, this may be set as the default value.
A default value is the value that is inserted into a column when an explicit value is not specified in an INSERT statement. A default value can be a literal character string that you define or one of the following SQL constant expressions: USER.
In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument.
C# 4 allows named arguments and optional parameters1:
int Sum (int a = 9, int b = 4)
{
return a + b;
}
Then:
Sum(10, 5); // Positional arguments as "normal"
Sum(b: 5); // Use the default value for a
Sum(a: 5); // Use the default value for b
Sum(); // Default both parameters
Sum(b: 1, a: 10); // Arguments can be reordered
EDIT: For overloaded methods, if there are multiple matches the compiler checks whether any of those candidates are only valid due to giving default values. If that's the case, those candidates are effectively given priority. This is one of the tie-breaking rules listed in section 7.5.3.2. There's no preference for just using "fewer" default values; it's an all or nothing approach. I give an example of this in my article on overloading.
1 It's unfortunate that the terminology is often confused, even by Microsoft. Parameters have always have names - what's new is that you can specify the name in the calling code, for the argument. On the other hand, you make the parameter optional by specifying a default.
With C# 4 you can do int someValue = sum (b: 14);
EDIT - as per comments:
C++ can have default values for parameters... these parameters can be "skipped" when calling a method/function BUT the rule in C++ is that only the right-most parameters can be skipped... which makes it possible in C++ to call sum()
and sum (7)
refering to a
but NOT the call you give as an example...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With