Hello one more time guys,
So I think the most of you are familiar with string.IsNullOrEmpty method which is very useful when you’re checking your string on actually having the data for different reasons:
- Sometimes we need to parse the string
- Add something to the string
- Use some of the string members
- AND try to see if the data from the database/xml/file is valid.
But now another problem is around: often the data in database has some whitespaces because there are constraints on some varchar columns NOT NULL. To works these around when something is not available, someone could insert a whitespace, and this would solve the problem, for the moment.
Actually it’s not a lot of fun to do something like
if (!string.IsNullOrEmpty(" ") && " ".Trim() != string.Empty)
{
}
What’s why .NET framework 4.0 has the string.IsNullOrWhiteSpace method.
To compare there 2 methods I did the following program:
using System;
using System.Collections.Generic;
namespace Intro.StringIsNullOrWhiteSpace
{
class Program
{
///
/// The main entry point for the application.
///
static void Main(string[] args)
{
// let's say we have a Dictionary of int - string
// the string representation of a number. Example: 1 - one
Dictionary integerDictionary = new Dictionary();
integerDictionary.Add(1, "one");
integerDictionary.Add(2, "two");
integerDictionary.Add(300, "three hundreds");
integerDictionary.Add(4, "four");
integerDictionary.Add(67, "sixty seven");
// let's assume that we don't know anything about the data in the dictionary
// we also could have something like
integerDictionary.Add(5000, null);
integerDictionary.Add(50001, string.Empty);
integerDictionary.Add(56565, " ");
integerDictionary.Add(23, " \r\n ");
// now let's check it with string.IsNullOrEmpty
Console.WriteLine("string.IsNullOrEmpty");
Console.WriteLine("===================================");
foreach (var keyValuePair in integerDictionary)
{
if (string.IsNullOrEmpty(keyValuePair.Value))
{
Console.WriteLine(keyValuePair.Value + " - True");
}
else
{
Console.WriteLine(keyValuePair.Value + " - False");
}
}
Console.ReadKey();
Console.WriteLine(Environment.NewLine);
// let's check it now with the new one : string.IsNullOrWhiteSpace
Console.WriteLine("string.IsNullOrWhiteSpace");
Console.WriteLine("===================================");
foreach (var keyValuePair in integerDictionary)
{
if (string.IsNullOrWhiteSpace(keyValuePair.Value))
{
Console.WriteLine(keyValuePair.Value + " - True");
}
else
{
Console.WriteLine(keyValuePair.Value + " - False");
}
}
Console.ReadKey();
}
}
}
Here is the output of the program:
Have a nice day and use it in .NET 4.0 !