Passing an empty array as default value of an optional parameter

C#Default ValueOptional Parameters

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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];

Solution 2 - C#

If you can make the array the last argument you could also do this:

public void DoSomething(int index, bool wasThirdParam = true, params ushort[] array)

The compiler will automatically pass an empty array if it is not specified, and you get the added flexibility to either pass an array as a single argument or put the elements directly as variable length arguments to your method.

Solution 3 - C#

I know it's an old question, and whilst this answer doesn't directly solve how to get around the limitations imposed by the compiler, method overloading is an alternative:

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

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

      ...
   }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMandoMandoView Question on Stackoverflow
Solution 1 - C#Lasse V. KarlsenView Answer on Stackoverflow
Solution 2 - C#chknView Answer on Stackoverflow
Solution 3 - C#DariusView Answer on Stackoverflow