c# - Passing argument to Class method -


i have problem passing argument class. want pass every iteration fill array.

private string[,] links;              (int = 0; < 40; i++)             {                 links = sql.link(i);             } 

and that's method inside class:

public string[,] link(int i) {     sqlcommand sqlcommand = new sqlcommand();     string[,] array = new string[40,40];     int num = 0;     sqlcommand.connection = this.conn;     sqlcommand.commandtext = "select top (40) link dbo.links";     sqldatareader sqldatareader = sqlcommand.executereader();     while (sqldatareader.read())     {         array[i,num] = sqldatareader.getvalue(0).tostring();                                 num++;     }     sqldatareader.close();     return array; } 

the thing is, links array contains nulls.

when change passing code to:

links = sql.link(0); 

then every index 0,0 0,39 filled. why passing not work properly?

because, in following line

string[,] array = new string[40,40]; generating new array , returning same.

so during first iteration of loop, in links = sql.link(i); links array contain values links[0, 0] through links[0, 39], in next iteration, new array object returned, links point new object (which hold values [1, 0] through [1, 39]).

in current case, after lop completed, links array variable contains values [39, 0] through [39, 39] not others.

possible approaches

the solution array , merge previous one. 2 approaches shown below reference:

1) returning array index in 1 iteration , merge previous data

private string[,] links = links[40, 40];  for(int = 0; < 40; i++) {     string[] linkspart = link(i);      for(int j = 0; j < 40; j++)     {         links[i, j] = linkspart[j];     }     // here, links array variable contain values [0, 0] through [40, 40]      //...rest of code. }  string[] link(int i) {     string[] linkparts = new string[40];      //connection open , populate array code goes here } 

2) passing array parameter link function

private string[,] links = links[40, 40];  for(int = 0; < 40; i++) {     link(i, links);      // here, links array variable contain values [0, 0] through [40, 40]      //...rest of code. }  string[] link(int i, string[,] arr) {     // no need create new array      //connection open , other code (before sqldatareader.read() line)     while (sqldatareader.read())     {        arr[i , num] = sqldatareader.getvalue(0).tostring();         num++;     }      //rest of code , return statement } 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -