Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default method parameters in C#

How can I make a method have default values for parameters?

like image 786
Mehdei Avatar asked Aug 14 '10 08:08

Mehdei


2 Answers

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:

  • The parameterless constructor of a value type
  • 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.)

like image 107
Jon Skeet Avatar answered Nov 02 '22 22:11

Jon Skeet


A simple solution is to overload the method:

private void Foo(int length)
{
}

private void Foo()
{
    Foo(20);
}
like image 22
Kobi Avatar answered Nov 03 '22 00:11

Kobi