Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsNullOrEmptyOrWhiteSpace method missing

Tags:

c#

.net

I define a string and check it by string.IsNullOrEmptyOrWhiteSpace().

But I got this error:

'string' does not contain a definition for 'IsNullOrEmptyOrWhiteSpace' and no extension method 'IsNullOrEmptyOrWhiteSpace' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) D:\project\project\Controllers\aController.cs 23 24 project

What is the reason?


2 Answers

String.IsNullOrWhiteSpace has been introduced in .NET 4. If you are not targeting .NET 4 you could easily write your own:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        if (value != null)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (!char.IsWhiteSpace(value[i]))
                {
                    return false;
                }
            }
        }
        return true;
    }
}

which could be used like this:

bool isNullOrWhiteSpace = StringExtensions.IsNullOrWhiteSpace("foo bar");

or as an extension method if you prefer:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        if (value != null)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (!char.IsWhiteSpace(value[i]))
                {
                    return false;
                }
            }
        }
        return true;
    }
}

which allows you to use it directly:

bool isNullOrWhiteSpace = "foo bar".IsNullOrWhiteSpace();

For the extension method to work make sure that the namespace in which the StringExtensions static class has been defined is in scope.

like image 131
Darin Dimitrov Avatar answered Sep 12 '25 15:09

Darin Dimitrov


Here's another alternative implementation, just for fun. It probably wouldn't perform as well as Darin's, but it's a nice example of LINQ:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return value == null || value.All(char.IsWhiteSpace);
    }
}
like image 35
Jon Skeet Avatar answered Sep 12 '25 14:09

Jon Skeet