Mehdei
Mehdei

Reputation: 255

Default method parameters in C#

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

Upvotes: 12

Views: 22981

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503859

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.)

Upvotes: 16

Oded
Oded

Reputation: 499382

You simply declare them with the default values - they are called optional parameters:

 public void myMethod(string param1 = "default", int param2 = 3)
 {
 }

This was introduced in C# 4.0 (so you will need to use visual studio 2010).

Upvotes: 8

Kobi
Kobi

Reputation: 138147

A simple solution is to overload the method:

private void Foo(int length)
{
}

private void Foo()
{
    Foo(20);
}

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

C# 4.0 allows you to use named and optional arguments:

public void ExampleMethod(
    int required, 
    string optionalstr = "default string",
    int optionalint = 10
)

In previous versions you could simulate default parameters by using method overloading.

Upvotes: 12

Related Questions