Optional Multidimensional Arrays as Arguments in C#

arrays, c#, multidimensional-array

Solution

It's not possible to do this directly but you can get a similar effect by doing the following pattern

private String communicateToServer(String serverHostname,
                                   String[,] disk = null,
                                   String[,] hdd= null,
                                   String[,] nic= null) {

   disk = disk ?? new string[] {{"dummy","dummy"}},
   hdd= hdd ?? new string[] {{"dummy","dummy"}}
   nic= nic ?? new string[] {{"dummy","dummy"}}

    ...
}

Essentially use `null` as the default and if `null` is the value convert to the actual default. This does mean that an explicit `null` being passed will be interpreted as the default value though.

Problem

I want to declare a function that has 1 required argument and 4 optional 2D array arguments, how do i do so? I know to make an argument optional, we should place a value in it during function creation. I also saw what I did below is wrong and has a `"Array initializers can only be used in a variable or field initializer. Try using a new expression instead."` Error ``` private String communicateToServer(String serverHostname, String[,] disk = new string[] {{"dummy","dummy"}}, String[,] hdd= new string[] {{"dummy","dummy"}} String[,] nic= new string[] {{"dummy","dummy"}} String[,] disk = new string[] {{"dummy","dummy"}} ) ```

Original source