Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) 
{
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading