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.
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 .
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With