Saturday, June 1, 2013

Best Code practice C#

Use int.TryParse( ) to keep away exception .
Convert.Int32 throws an exception of "System.FormatException" when the input parameter is wrong .

Example

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("Userid")); //Here it will throw an Exception.

int employeeAge = 0;
int.TryParse(Request.QueryString.Get("Userid");, 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)

No comments:

Post a Comment