Method parameter array default value
18,845
Solution 1
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);
}
}
Solution 2
Try this:
public void SomeMethod(String[] arrayString = null)
{
arrayString = arrayString ?? {"value 1", "value 2", "value 3"};
foreach(someString in arrayString)
{
Debug.WriteLine(someString);
}
}
someMethod();
Related videos on Youtube
Author by
Gabi Barrientos
Updated on September 26, 2022Comments
-
Gabi Barrientos over 1 year
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?-
BimoThere 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.
-
-
Gabi Barrientos over 11 yearsOk, thanks. I will have a go at this. I will accept this as my answer in about 11 minutes.
-
Gabi Barrientos over 11 yearsThanks 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.
-
Reed Copsey over 11 years+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.
-
John over 6 yearsWhat about
int[] arrayString
? I tried witharrayString = arrayString ?? { 0 };
but I got the compiler errorCS1525: Invalid expression term '{'
-
John over 6 yearsIt's okay I got it resolved by changing it to
arrayString = arrayString ?? new int[] { 0 };