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?
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):
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With