As others have said, default values can't be arrays. However, one way of avoiding this is to make the default value null and then initialize the array if necessary:
public void Foo(int[] x = null)
{
x = x ?? new int[] { 5, 10 };
}
Or if you're not going to mutate the array or expose it to the caller:
private static readonly int[] FooDefault = new int[] { 5, 10 };
public void Foo(int[] x = null)
{
x = x ?? FooDefault;
}
Note that this assumes null
isn't a value that you'd want to use for any other reason. It's not a globally applicable idea, but it works well in some cases where you can't express the default value as a compile-time constant. You can use the same thing for things like Encoding.UTF8
as a default encoding.
If you want a value type parameter, you can just make that a nullable one. For example, suppose you wanted to default a parameter to the number of processors (which clearly isn't a compile-time constant) you could do:
public void RunInParallel(int? cores = null)
{
int realCores = cores ?? Environment.ProcessorCount;
}