One thing I often find myself having to do is validate a string for not being empty. One fairly primitive way to accomplish this is to test for the following condition in an if statement:
input.Equals(string.Empty)This will return true if input is an empty string. Sometimes, however, you need to also test if the input contains empty white space. Imagine if the user accidently hit the space key and the value for input was the string " ". The test above would return false in such a case. To cater for such scenarios, I wrote the following extension method in a class library project.
public static bool IsNullOrEmptyWhiteSpace(this string str) { return (str == null || str.Trim().Equals(string.Empty)); }The test would now look like:
if (input.IsNullOrEmptyWhiteSpace()) //Tell user to enter something** Update (13/03/2013) **
As of .NET 4 the static method IsNullOrWhiteSpace was added to the String datatype, therefore making the extension method above redundant (unless you're still using earlier versions of the framework :).
No comments:
Post a Comment