views:

133

answers:

6

How i can make the method have a default values for parameters ?

+5  A: 

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

Oded
Can the downvote please explain?
Oded
@Ardman: OP may have meant C# 4.
dalle
+6  A: 

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.

Darin Dimitrov
+6  A: 

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

Jon Skeet
+1  A: 

A simple solution is to overload the method:

private void Foo(int length)
{
}

private void Foo()
{
    Foo(20);
}
Kobi
This is still a good solution, even in C# 4. One advantage of this is that the default values are embedded in your assembly rather than the callers'; see Jon's answer for more details.
Dan Bryant
@Dan: I've become increasingly skeptical about the *real* damage of the "you can't change default values" issue... because for most code, I expect that the whole app will be recompiled anyway. It's something worth knowing about, but I don't think it's really a huge issue.
Jon Skeet
@Jon, I'm inclined to agree with you, as I think it would probably be bad practice to rely on particular default values, in any case, as that would seem to indicate that the nature of the API has changed. If that's the case, the client probably needs to change anyway.
Dan Bryant
A: 

Read this article on named and optional arguments.

thelost