Skip to content

How to add a default value for a string array in a method?

Posted in Education, and WhoCodeFirst

In C# code, you can’t provide an empty array as a default parameter value because it is not a compile-time constant.

One way to work around this limitation is to use null as the default value and then check for it inside the method. If the parameter is null, you can create a new empty array before using it:

void Foo(string[] param = null) {
     if (param == null) {
         param = new string[0];
     }
     // rest of the method implementation
 }

Another way to achieve this is to use an optional parameter with the params keyword which allows you to pass a variable number of arguments to the method.

void Foo(params string[] param) {
     if (param == null) {
         param = new string[0];
     }
     // rest of the method implementation
 }

And now you can call the method without passing any argument and it will be considered as empty array.

Foo();

The above scenario, to allows you to call the method with an explicit empty array, or with no arguments at all, and the method will treat them the same way.

Happy Learning!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *