21

In c# it is possible to use default parameter values in a method, in example:

public void SomeMethod(String someString = "string value")
{
    Debug.WriteLine(someString);
}

But now I want to use an array as the parameter in the method, and set a default value for it.
I was thinking it should look something like this:

public void SomeMethod(String[] arrayString = {"value 1", "value 2", "value 3"})
{
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}

But this does not work.
Is there a correct way to do this, if this is even possible at all?

colinfang
  • 20,909
  • 19
  • 90
  • 173
Gabi Barrientos
  • 1,746
  • 3
  • 23
  • 37
  • 2
    There is a workaround for reference types. Set the argument default to "null". Then, inside the code block check if parameter is set to null, if it is null set the default value for the reference type parameter. – Bimo Sep 26 '17 at 20:00

2 Answers2

29

Is there a correct way to do this, if this is even possible at all?

This is not possible (directly) as the default value must be one of the following (from Optional Arguments):

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

Creating an array doesn't fit any of the possible default values for optional arguments.

The best option here is to make an overload:

public void SomeMethod()
{
    SomeMethod(new[] {"value 1", "value 2", "value 3"});
}


public void SomeMethod(String[] arrayString)
{
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
18

Try this:

public void SomeMethod(String[] arrayString = null)
{
    arrayString = arrayString ?? {"value 1", "value 2", "value 3"};
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}
someMethod();
Nathan
  • 2,705
  • 23
  • 28
  • Thanks for your input. It seems like a good way to go, however I am going to stick with Reed's answer on this one because it comes in handy in some other ways as well for me. – Gabi Barrientos Sep 26 '12 at 17:40
  • 5
    +1 This is a slick approach, but it doesn't give you a way to differentiate between a user passing in null *explicitly* and just not using the parameter (which is why I typically prefer the overload approach). That may or may not be important in this case. – Reed Copsey Sep 26 '12 at 17:42
  • What about `int[] arrayString`? I tried with `arrayString = arrayString ?? { 0 };` but I got the compiler error `CS1525: Invalid expression term '{'` – Dan Oct 31 '17 at 02:51
  • 4
    It's okay I got it resolved by changing it to `arrayString = arrayString ?? new int[] { 0 };` – Dan Oct 31 '17 at 02:57