2009/06/18

Tips: Use String.IsNullOrEmpty() instead of != "" to check empty string

According to FxCop's recommendation, use String.IsNullOrEmpty() is a good approach to check the String is empty or not.

Case 1:
//No good
strUsername != ""
Case 2:
//Better
strUsername.Length != 0
Case 3:
//The Best
!String.IsNullOrEmpty(strUsername)
Reason: Equals requires more MSIL instructions than the other two. Length will throw an exception if the string is null. IsNullOrEmpty has the same performance with Length but also takes care of the null problem.

Go here for more detail information and example.

No comments:

Post a Comment