Collection objects have Add() method in .NET. It is very important to understand how it works.
Code Block 1:
TableRow row = new TableRow();
for (int i = 0; i < resultFields.Count; i++)
{
foreach(string str in resultFields[i])
{
TableCell cell = new TableCell();
cell.Text = str;
this.Response.Write(str);
row.Cells.Add(cell);
}
tbl_rsltFields.Rows.Add(row);
}
In this example, if resultFields.Count is 2, how many rows do you think are in the tbl_rsltFields?
The answer is 1. It is worth noticing this case.
Code Block 2:
for (int i = 0; i < resultFields.Count; i++)
{
TableRow row = new TableRow();
foreach(string str in resultFields[i])
{
TableCell cell = new TableCell();
cell.Text = str;
this.Response.Write(str);
row.Cells.Add(cell);
}
tbl_rsltFields.Rows.Add(row);
}
In this case, the answer is 2.
Actually, if we try to add "row.Cells.Clear();" right after "tbl_rsltFields.Rows.Add(row)" in code block 1, there will be nothing contained in tbl_rsltFields at last. Based on this fact, we know that by calling Add() method, it only gets a copy of the reference, instead of making a copy of the whole row. So it acts like it is passing reference by value.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment