Wednesday, January 30, 2008

Add() method in .NET (passing parameter)

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.

Wednesday, January 23, 2008

Application["UserCount"] += 1 doesn't work

Why does Application["UserCount"] += 1; incur compiler error? It's the same reason why Application["UserCount"] = Application["UserCount"] + 1; doesn't work either.

And once you know the correct way should be: Application["UserCount"] = (int)Application["UserCount"] + 1; you'll also know (int)Application["UserCount"] += 1; is wrong too.