Method parameter array default value [duplicate]
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); }}
Try this:
public void SomeMethod(String[] arrayString = null){ arrayString = arrayString ?? {"value 1", "value 2", "value 3"}; foreach(someString in arrayString) { Debug.WriteLine(someString); }}someMethod();