Which of the two code segments below would you prefer? Why? Are there any circumstances where the other would be preferable? Could you make any further improvements?
i.
private int GetSize(string deptName)
{
QueryHelper dqh = new QueryHelper();
return dqh.GetDataSet("sp_GetDeptSize",deptName).Tables[0].Rows[0]["Size"];
}
ii.
private int GetSize(string deptName)
{
QueryHelper dqh = new QueryHelper();
DataSet ds = dqh.GetDataSet("sp_GetDeptSize", deptName);
DataTable dt = ds.Tables[0];
DataRow dr = dt.Rows[0];
int size = dr["Size"];
return size;
}
Please note that QueryHelper is custom type.
My answer to this: I prefer to method i, which is more concise. It seems that method ii is not preferable under any circumstances.
I need advice on further improvement on method i, and idea would be very much appreciated.
The two methods you listed are 99% identical. The notational difference is a matter of taste.
Both still need a cast to int
.
I would prefer skipping the DataSet and use Command.ExecuteScalar()
Given the code, i will say Method 2 is better as you must NULL check everything before trying to access.
what if dataset it NULL?. Method 1 will error out.
What if there is no table in the dataset? Again method 1 will error out.
What if there is a table but no row? Again method 1 will error out.
精彩评论