Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method parameter array default value [duplicate]

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?

like image 664
Gabi Barrientos Avatar asked Sep 26 '12 17:09

Gabi Barrientos


2 Answers

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);
    }
}
like image 139
Reed Copsey Avatar answered Oct 16 '22 05:10

Reed Copsey


Try this:

public void SomeMethod(String[] arrayString = null)
{
    arrayString = arrayString ?? {"value 1", "value 2", "value 3"};
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}
someMethod();
like image 15
Nathan Avatar answered Oct 16 '22 04:10

Nathan