Possible Duplicate:
passing an empty array as default value of optional parameter in c#
This code is correct in C# 4.0
static void SomeMethod(int x, int y = 5, int z = 7)
{
}
SomeMethod(1);
but when applied on arrays it gives me errors
private static void diagonalFill(int[,] a,int[] fillType = {0,-1},int[] diagFill = {-1,1})
{
}
diagonalFill(array);
Could anyone show me the right way? 10x
Default parameter values are not possible with complex reference values. The first one works because the parameters are primitives that are stored on the stack and are copied by value. Arrays are complex reference values so they must first be allocated before they can appear as parameters.
Edit:
@Henk Holterman's comment is well taken. I don't have direct knowledge of whether the stack or heap come into play on this so this information is either mistaken or misleading. The primary criteria I am aware of is that only primitives types can be used. From this document,
A default value must be one of the following types of expressions:
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.
The "primitives" list link above has been modified for 2010 to be called "built-in" types. It can be found here.
A default parameter value must be a compile time constant, so you can't do this.
You can't use initializers as default.
You could use:
private static void diagonalFill(int[,] a,
int[] fillType = null,
int[] diagFill = null)
{
if (fillType == null)
fillType = new int[] {0,-1};
if (diagFill == null)
diagFill = new int[] {-1,1};
...
}
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