Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set initialized arrays as parameters in C# [duplicate]

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

like image 650
kidwon Avatar asked Nov 08 '11 23:11

kidwon


Video Answer


3 Answers

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:

  1. a constant expression;

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

  3. 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.

like image 193
Joel Etherton Avatar answered Oct 13 '22 07:10

Joel Etherton


A default parameter value must be a compile time constant, so you can't do this.

like image 39
AndrewC Avatar answered Oct 13 '22 07:10

AndrewC


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};

  ... 
}
like image 2
Henk Holterman Avatar answered Oct 13 '22 05:10

Henk Holterman