by Edward
19 February 2010 14:11
String.IsNullOrWhiteSpace - New method available in .NET Framework 4
I found a very nice addition to the .NET Framework(version 4) while experimenting with code in Visual Studio 2010. There is a new method called "IsNullOrWhiteSpace", which is more powerful than the more familiar "IsNullOrEmpty" method. Incase you were wondering, the "IsNullOrEmpty" method is still available to be used.
For example, the common whitespace symbol " " represents a blank space, as used between words and sentences. The most common whitespace characters may be typed via the space bar or the Tab key. Depending on context, a line-break generated by the Return key (Enter key) may be considered whitespace as well. This brings concerns when using the "IsNullOrEmpty" method.
Introducing "IsNullOrWhiteSpace"! In the .NET Framework 4, string.IsNullOrWhiteSpace() will return true if a string is full of whitespace characters. I found this very helpful when dealing with getting XML data from external web services.
Here is a short example of how to use this new method.
1: static void Main(string[] args)
2: {
3: // set some test values
4: string[] testValues = { null, String.Empty, "ABCDE",
5: new String(' ', 20), " ",
6: new String(' ', 10) };
7: //loop through the list and return result
8: foreach (string value in testValues)
9: {
10: Console.WriteLine("Return is: " +
11: String.IsNullOrWhiteSpace(value));
12: }
13: // we want to see the return
14: Console.ReadLine();
15: }