How can I make a method have default values for parameters?
You can only do this in C# 4, which introduced both named arguments and optional parameters:
public void Foo(int x = 10)
{
Console.WriteLine(x);
}
...
Foo(); // Prints 10
Note that the default value has to be a constant - either a normal compile-time constant (e.g. a literal) or:
default(T)
for some type T
Also note that the default value is embedded in the caller's assembly (assuming you omit the relevant argument) - so if you change the default value without rebuilding the calling code, you'll still see the old value.
This (and other new features in C# 4) are covered in the second edition of C# in Depth. (Chapter 13 in this case.)
A simple solution is to overload the method:
private void Foo(int length)
{
}
private void Foo()
{
Foo(20);
}
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