tags:

views:

500

answers:

7

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?

+31  A: 

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.

Darin Dimitrov
@Darin, you are absolutely right, the method is enabled only in .NET 4 .0 and .NET Client Profile 4.0
Boris Modylevsky
+1, and I would make it an extension method!
KMan
A question please, Why the inner for loop instead of value.trim()!=string.empty ?
Jonathan
@Jon, this way you don't have to create a new string, and can return false as soon as you find the first non-whitespace character (Trim will look at characters at the beginning *and* end, until it finds non-whitespace). `TrimStart` wouldn't be as bad, but you're still creating a new (possibly long) string unnecessarily.
Matthew Flaschen
@Thanks Matthew!
Jonathan
@KMan, it's considered bad practice to allow extension methods to run properly if the extended `this` parameter is null. It would be inconsistent with the behavior of other object references to not throw an ArgumentNullException within your extension method in this scenario. This is according to Microsoft's recommendations.
uosɐſ
+5  A: 

Maybe IsNullOrWhiteSpace is the method you are searching for? http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

jhominal
+10  A: 

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);
    }
}
Jon Skeet
Since `.All()` also returns true if value is empty, this is probably exactly what OP is looking for.
BlueRaja - Danny Pflughoeft
A: 

Funny enough nobody makes use of the Trim function here:

public static class StringExtensions
{
    public static bool IsNullOrEmptyOrWhiteSpace(this string value)
    {
        return string.IsNullOrEmpty(value)
                    ? true
                    : ReferenceEquals(value, null)
                            ? true
                            : string.IsNullOrEmpty(value.Trim(' '))
                                ? true
                                : false;
    }
}

Update: I see in the comments now it was proposed and rejected for various reasons, but there it is if one prefers brevity over efficiency...

flq
@Frank: How is that briefer than my version? I'd also suggest that using || is rather more readable than using the conditional operator here.
Jon Skeet
@Jon, it's not. I will restrain myself from posting on SO on Sundays :)
flq
What a convoluted way to write some simple logic! I'm tempted to give it -1, but it's not "wrong", just not easy to read.
Evgeny
what about the "if" statement?
Eric
+1  A: 

I have used (in .NET v2.0):

public static class StringExtensions
{
    public static bool IsNullOrEmptyOrWhitespace(this string value)
    {
        return string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim());
    }
}

The Trim() method will remove all leading or trailing whitespace so if your string is entirely whitespace, it will be reduced to the empty string.

I can't say that performance has been an issue.

Dr Herbie
>>I have used (in .NET v2.0):How can you use Extension method in NET2.0 since it was introduced in NET3.5?
Arseny
Originally, in VS2005 this was a utility method (remove 'this' from the first parameter). Later we moved to VS2008, while still targetting .net2.0 and fudged the use of extension methods (this is a compiler feature, not a .NET Framework feature) using this method: http://geekswithblogs.net/robp/archive/2007/12/20/using-extension-methods-in-.net-2.0-with-visual-studio-2008.aspx. Now we're on .NET 3.5 so we lost the fudge.
Dr Herbie
A: 

I am sure that you need:

    public static bool IsNullOrEmptyOrWhiteSpace(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return true;
        else if (IsWhiteSpace(s))
            return true;
        else
            return false;
    }
steven spielberg
-1 . bullocks answer to redefine something already there...
TomTom
-1 for not checking the Microsoft's source code or using .NET Reflector.
AMissico
It isn't even correct, either. This isn't valid c#. It wouldn't even be if the missing "Char." was there, because the function IsWhiteSpace has no overload that takes only a string.
qstarin
Not to mention @Darin Dimitrov answered the question correctly, and quite well, 5 days prior to this answer.
qstarin
Something smells fishy!
palswim
Sigh, only 141 downvotes to go...
Will
Okay, guys, stop flagging this. Yes, its awful. No, it should have never been selected as the answer. No, it is not worthy of a bounty. No, nobody liked Indiana Jones 4. Only @4thpage and spielberg here can do anything about it. The rest of you can downvote answers you hate and upvote answers you like. If you have any more issues with how stackoverflow works, take it to meta.stackoverflow.com. Thanks.
Will
A: 

Exact copy from Microsoft's source code for .NET 4 Framework, ..\RefSrc\Source.Net\4.0\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\clr\src\BCL\System\String.cs\1305376\String.cs

    public static bool IsNullOrEmpty(String value) {
        return (value == null || value.Length == 0); 
    }

    public static bool IsNullOrWhiteSpace(String value) {
        if (value == null) return true; 

        for(int i = 0; i < value.Length; i++) { 
            if(!Char.IsWhiteSpace(value[i])) return false; 
        }

        return true;
    }

Remarks

(from http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx)

IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

White-space characters are defined by the Unicode standard. The IsNullOrWhiteSpace method interprets any character that returns a value of true when it is passed to the Char.IsWhiteSpace method as a white-space character.

AMissico