Wednesday, September 26, 2007

Best Practices for Convert Class

1) Considered the following usage:
string userID = db.ExecuteScalar(dbCommand).ToString();

Better approach might be to use the Convert class
string userID = Convert.ToString(db.ExecuteScalar(dbCommand));

2) Considered the following usage:
if (dr["someColBool"] != null && dr["someColBool"].ToString().Length > 0 && Convert.ToBoolean(dr["someColBool"]) == true) continue;

Remove the unnecessary code and use one of the approaches:
if (Convert.ToBoolean(dr["someColBool"]) == true) continue;

or

if (Convert.ToBoolean(dr["someColBool"])) continue;

The above code works even if we have a null value for column "someColBool" in the DataRow instance. A null argument is a valid argument to various static convert methods on the Convert class, however, you can not pass empty string because it can't properly parse empty string.
When a null argument is passed it returns the default value for that value type.

3) Using Exceptions to catch invalid conversions
try
{
tbCurrentSomeColDate.Text = Convert.ToDateTime(dsTopSection.Tables[0].Rows[0]["someColDate"]).ToShortDateString();
}
catch (Exception)
{
Not a valid date
tbCurrentSomeColDate.Text = "";
}


General rule of thumb is to not to cast a wide net to catch all Exceptions if you can determine
during design time what exceptions might occur then put the code in place so that those exceptions would not thrown and only catch those exceptions that cannot be predetermined.

Another guideline is that if we can avoid causing an exception to be thrown, use that code instead of putting the code in a try ... catch statement.

A better approach might be to use the following code:

Object date = dsTopSection.Tables[0].Rows[0]["someColDate"];
DateTime dt;
if (date != null && DateTime.TryParse(date.ToString(), out dt))
tbCurrentSomeColDate.Text = dt.ToShortDateString();
else
tbCurrentSomeColDate.Text = "";


I am sure there are other better ways to use the Convert class and I would love to hear from the readers what are different ways they use the Convert class.

Happy Coding!