Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Multidimensional Arrays as Arguments in C#

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"}}
)
like image 890
Fukkatsu Avatar asked Oct 29 '25 06:10

Fukkatsu


1 Answers

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.

like image 79
JaredPar Avatar answered Oct 31 '25 21:10

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!