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
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:
Or if you’re not going to mutate the array or expose it to the caller:
Note that this assumes
nullisn’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 likeEncoding.UTF8as 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: