Home > front end >  How can I add a default value for a string array in a method?
How can I add a default value for a string array in a method?

Time:01-29

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.

CodePudding user response:

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) 
{
}

CodePudding user response:

You can use an optional parameter with the params keyword which allows you to pass a variable number of arguments to the method.

You can refer to this page. https://geeksnewslab.com/how-to-add-a-default-value-for-a-string-array-in-a-method/

CodePudding user response:

The default value must be one of the following in C# :

  1. A constant expression;

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

  3. An expression of the form default(ValType), where ValType is a value type."

The arrays you created don't follow any of the above rules of C#, and it is a reference type so there can be only one default value which is: null

And one more thing, Array is a reference type, so it initializes by new keyword so anything which initializes by new cannot be constant thus constant of the reference type is null

So You can use = null or = default

void Foo(string[] param = null) {
  param = param==null ? new[] : param;
}

OR

void Foo(string[] param = default) {
}
  • Related