Couple of Best Practices while Writing ASP.NET Code

Use int.TryParse() to keep away from Exception.

While using the Convert.ToInt32(), if the input parameter is of a wrong format and if it cannot be converted into an integer, then an exception of type "System.FormatException" will be thrown, but in case of the int.TryParse() no Exception will be thrown.

Example

If we are converting a QueryString value to an 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 the bool.TryParse, float.TryParse, double.TryParse, etc. for converting into other datatypes.

Convert .ToString() V/S obj.ToString()

Use the Convert.ToString(), because if you are using the obj.ToString() and the object(obj) value is null, it will throw an exception of type "System.NullReferenceException".

The cause of the exception is null because it doesn't have a method called ToString().

Example 

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 the 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 the String class.

So it's 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 the type "System.NullReferenceException".

String. IsNullorEmpry() V/S ("" || null)

Suppose you want to check a string for both its emptiness and nullability, then it's better to use the String.IsNullOrEmpty() instead of ("" || null).

Because "" will create a new object but the String.IsNullOrEmpty() will not do so. So it's better to use

if(String.IsNullOrEmpty("Devi")) instead of

if("Devi" == "" || "Devi" == null)

Visit my blog for more details:

erkunalpatel

Ebook Download
View all
Learn
View all