Note: This post is part of a series and you can find the rest of the parts in the series index.
I would guess strings are the most used type in .NET, so it is great to see some small improvements with them in .NET 4.
IsNullOrWhiteSpace
Since .NET 2.0 we have had the very useful IsNullOrEmpty which let us check for empty strings, but what about strings that contained nothing but white space? Unfortunately that would not be identified as empty! With .NET 4 we have a new method, IsNullOrWhiteSpace, which checks if a string is null, empty and if it is not just white space! Example usage:
string nullString = null; string emptyString = string.Empty; string blankString = emptyString.PadRight(30, ' '); string notBlankString = "SADev.co.za"; Console.WriteLine("IsNullOrEmpty"); Console.WriteLine("\t nullString is: {0}", string.IsNullOrEmpty(nullString)); Console.WriteLine("\t emptyString is: {0}", string.IsNullOrEmpty(emptyString)); Console.WriteLine("\t blankString is: {0}", string.IsNullOrEmpty(blankString)); Console.WriteLine("\t notBlankString is: {0}", string.IsNullOrEmpty(notBlankString)); Console.WriteLine("IsNullOrWhiteSpace"); Console.WriteLine("\t nullString is: {0}", string.IsNullOrWhiteSpace(nullString)); Console.WriteLine("\t emptyString is: {0}", string.IsNullOrWhiteSpace(emptyString)); Console.WriteLine("\t blankString is: {0}", string.IsNullOrWhiteSpace(blankString)); Console.WriteLine("\t notBlankString is: {0}", string.IsNullOrWhiteSpace(notBlankString));
This produces
The important one to note is blankString, in the second set (line 15 of the code) has a different result compared to it’s result in the first set.
Join & Concat
Join allows us to concatenate an array of strings together with a specific separator character in place. For example:
string[] someValues = { "This", "is", "a", "list", "of", "strings" }; Console.WriteLine(string.Join(Environment.NewLine,someValues));
This produces
Concat does the same thing, except there is no separate character. Example:
string[] someValues = { "This", "is", "a", "list", "of", "strings" }; Console.WriteLine(string.Concat(someValues));
This produces:
Both these methods fails when we start working with generic lists, like List<T> as they were not supported. This meant you often ended up calling .ToArray on the list and taking the performance impact. Now new overloads have been added to string which cater for IEnumerable<T> so we no longer need to ToArray the list. Now we can pass the list directly in, as in the following example:
List<string> someValues = new List<string>() { "This", "is", "a", "list", "of", "strings" }; Console.WriteLine(string.Join(Environment.NewLine, someValues));