Passing an empty array as default value of an optional parameter

MandoMando picture MandoMando · Aug 13, 2010 · Viewed 71.1k times · Source

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.

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Aug 13, 2010

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