Search code examples
c#parametersdefault

How can I add a default value for a string array in a method?


I have a method that takes a string[] as parameter, but I am unable to provide it with a default:

void Foo(string[] param = new[]) {
}

complains that the default should be a compile time constant. But what compile time constant is there as an empty array?

I know I can use default, but I was wondering what the syntax was explicitly, if at all possible.


Solution

  • A default value must be compile time value and there are no compile time const arrays in C# and your options are:

    1. don't have a default value
    2. use null/default

    default will mean null so you'd have to change string[] to string[]?.

    void Foo(string[]? x = default) // OK. 
    {
    }
    
    
    void Foo(string[] x = default) // Cannot convert null literal to non-nullable reference type.
    {
    }
    

    To soften the blow you could:

    void Foo(string[]? x = default)  
    {
       string[] y = x ?? new string[] {};
    
       // use y below
    }
    

    or even:

    void Foo() => Foo(new string[] {});
    
    void Foo(string[] a) 
    {
    }