Sunday, March 26, 2006

Int.Parse Vs Convert.ToInt32

What is the essential difference between Int.Parse and Convert.ToInt32 ?

Well, The difference lies in the way both handles NULL value. When encountered a NULL Value, Convert.ToInt32 returns a value 0.On other hand,Parse is more sensitive and expects a valid value. so it would throw an exception when you pass in a NULL.

What i prefer to use is like following

int id = Request.QueryString["code"]==null ? -1 : Int32.Parse(Request.QueryString["code"]);

The reason behind this is simple.Suppose "id" is a value from database where "0" is valid value, Then using Convert.ToInt32 might lead to unexpected results. There are many more problems of same kind that may arise.