Software Technology Tips

Use int.TryParse() to keep away from Exception.
While using Convert.ToInt32(), if the input parameter is of wrong format and if it can not be convertable into integer then an exception of type "System.FormatException" will be thrown, but in case of int.TryParse() no Exception will be thrown.
e.g :-
If we are converting a QueryString value to integer and the QueryString value is "de8913jhjkdas", then -
int employeeID = 0;
employeeAge = Convert.ToInt32(Request.QueryString.Get("id")); //Here it will throw an Exception.
int employeeAge = 0;
int.TryParse(Request.QueryString.Get("id");, out employeeAge); //Here it will not throw any Exception.
You can also use bool.TryParse, float.TryParse, double.TryParse, etc for converting into other datatypes.
Convert.ToString() V/S obj.ToString()

Use Convert.ToString(), because if you are using obj.ToString() and the object(obj) value is null it will throw an excetion of type "System.NullReferenceException".
The cause of the exception is null doesn't have a method called ToString().
Response.Write("Name : " + Session["User_Name"].ToString());        //Here it will throw an Exception if Session["User_Name"] is null.
Response.Write("Name : " + Convert.ToString(Session["User_Name"])); //Here it will not throw any Exception.
 String.Empty V/S ""

If you want to check whether a string is empty or not then use String.Empty instead of "", because "" will create a new object in the memory for the checking while String.Empty will not create any object, because Empty is a read-only property of String class.
So its better to use if("Devi" == String.Empty) instead of if("Devi" == "").
You can also use if("Devi".Length == 0) for doing the same thing but if the string is null then it will throw an exception of type "System.NullReferenceException".
 String.IsNullorEmpry() V/S ("" || null)

Suppose you want to check a string for both its emptiness and nullability then its better to use String.IsNullOrEmpty() instead of ("" || null). Because "" will create a new object but String.IsNullOrEmpty() will not do so.
So its better to use if(String.IsNullOrEmpty("Devi")) instead of if("Devi" == "" || "Devi" == null)
Feel free to add more points to the list.

Related Tags:


Author: Devi Das


Let us Connect!

Awards and Achievements

Red Herringcolor DeloitteFast50 DB ZInnov1   Nascome  DB Stpi

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login