Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an empty array as default value of an optional parameter [duplicate]

How does one define a function that takes an optional array with an empty array as default?

public void DoSomething(int index, ushort[] array = new ushort[] {},  bool thirdParam = true) 

results in:

Default parameter value for 'array' must be a compile-time constant.

like image 644
MandoMando Avatar asked Aug 13 '10 20:08

MandoMando


People also ask

How do you pass an empty array?

If the array has a length of zero, then it does not contain any element. To return an empty array from a function, we can create a new array with a zero size. In the example below, we create a function returnEmptyArray() that returns an array of int . We return new int[0] that is an empty array of int .

Is it mandatory to specify a default value to optional parameter?

Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression. Every parameter following an optional parameter in the procedure definition must also be optional.

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.


1 Answers

You can't create compile-time constants of object references.

The only valid compile-time constant you can use is null, so change your code to this:

public void DoSomething(int index, ushort[] array = null,   bool thirdParam = true) 

And inside your method do this:

array = array ?? new ushort[0]; 

(from comments) From C# 8 onwards you can also use the shorter syntax:

array ??= new ushort[0]; 
like image 149
Lasse V. Karlsen Avatar answered Sep 17 '22 15:09

Lasse V. Karlsen