25

In c# it is possible to use default parameter values in a method, in example:

public void SomeMethod(String someString = "string value") { Debug.WriteLine(someString); } 

But now I want to use an array as the parameter in the method, and set a default value for it.
I was thinking it should look something like this:

public void SomeMethod(String[] arrayString = {"value 1", "value 2", "value 3"}) { foreach(someString in arrayString) { Debug.WriteLine(someString); } } 

But this does not work.
Is there a correct way to do this, if this is even possible at all?

1
  • 2
    There is a workaround for reference types. Set the argument default to "null". Then, inside the code block check if parameter is set to null, if it is null set the default value for the reference type parameter. Commented Sep 26, 2017 at 20:00

2 Answers 2

33

Is there a correct way to do this, if this is even possible at all?

This is not possible (directly) as the default value must be one of the following (from Optional Arguments):

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

Creating an array doesn't fit any of the possible default values for optional arguments.

The best option here is to make an overload:

public void SomeMethod() { SomeMethod(new[] {"value 1", "value 2", "value 3"}); } public void SomeMethod(String[] arrayString) { foreach(someString in arrayString) { Debug.WriteLine(someString); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks. I will have a go at this. I will accept this as my answer in about 11 minutes.
21

Try this:

public void SomeMethod(String[] arrayString = null) { arrayString = arrayString ?? {"value 1", "value 2", "value 3"}; foreach(someString in arrayString) { Debug.WriteLine(someString); } } someMethod(); 

5 Comments

Thanks for your input. It seems like a good way to go, however I am going to stick with Reed's answer on this one because it comes in handy in some other ways as well for me.
+1 This is a slick approach, but it doesn't give you a way to differentiate between a user passing in null explicitly and just not using the parameter (which is why I typically prefer the overload approach). That may or may not be important in this case.
What about int[] arrayString? I tried with arrayString = arrayString ?? { 0 }; but I got the compiler error CS1525: Invalid expression term '{'
It's okay I got it resolved by changing it to arrayString = arrayString ?? new int[] { 0 };
C# 8.0 has a Compound assignment operator (??=). So the assignment can be done arrayString ??= new [] {"value 1", "value 2", "value 3"};

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.