.NET 4 Baby Steps: Part II - String

Photo-0046Note: 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 lets us check for empty strings—but what about strings that contained nothing but whitespace? 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, or consists solely of whitespace. 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

image

The important one to note is blankString—in the second set (line 15 of the code), it has a different result compared to its result in the first set.

Join & Concat

Join allows us to concatenate an array of strings with a specific separator character. For example:

string[] someValues = { "This", "is", "a", "list", "of", "strings" };
Console.WriteLine(string.Join(Environment.NewLine, someValues));

This produces

image

Concat does the same thing, except there is no separator character. Example:

string[] someValues = { "This", "is", "a", "list", "of", "strings" };
Console.WriteLine(string.Concat(someValues));

This produces:

image

Both of these methods failed when working with generic lists, like List<T>, since they were not supported. This meant you often had to call ToArray() on the list, incurring a performance impact. Now, new overloads have been added to string that cater for IEnumerable<T>, so we no longer need to call ToArray(). Now we can pass the list directly in, as shown below:

List<string> someValues = new List<string>() { "This", "is", "a", "list", "of", "strings" };
Console.WriteLine(string.Join(Environment.NewLine, someValues));