Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4.0: Method parameter default values as array

Is it possible in C# 4.0 method default values parameters as array (for ex. string[] sArray)? if yes, how to implement it?

I tried call function like below:

MethodA(string[] legends=new string[]{"a","b"},float[] values=new float[]{1,2}, string alt="sd");

It's not work

like image 223
loviji Avatar asked Jun 29 '10 06:06

loviji


2 Answers

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;
}
like image 96
Jon Skeet Avatar answered Sep 21 '22 22:09

Jon Skeet


Default values must be compile-time constant, which means arrays cannot be used.

The standard (pg 312) says this:

The expression in a default-argument must be one of the following:

  • a constant-expression
  • an expression of the form new S() where S is a value type
  • an expression of the form default(S) where S is a value type
like image 22
Dean Harding Avatar answered Sep 21 '22 22:09

Dean Harding