Click here to Skip to main content
15,867,594 members
Articles / General Programming / String
Alternative
Tip/Trick

.NET 4: string.IsNullOrWhitespace()

Rate me:
Please Sign up or sign in to vote.
3.33/5 (2 votes)
12 Aug 2010CPOL 15.6K   1   3
public static class StringExtensions { public static bool IsNullOrWhitespace(this string s) { if (null == s) return true; return string.IsNullOrEmpty(s.Trim()); } }
C#
public static class StringExtensions
    {
        public static bool IsNullOrWhitespace(this string s)
        {
            if (null == s) return true;
            return string.IsNullOrEmpty(s.Trim());
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Livin in a lonely world, caught the midnight train going anywhere... Only thing is it was a runaway train... and it ain't ever goin back...
мала ка на хари, Trahentes ex exsilium

Comments and Discussions

 
GeneralThank you for clarifying however... Whitespace variants can... Pin
jfriedman13-Aug-10 10:30
jfriedman13-Aug-10 10:30 
GeneralRe: I assist carrol_jhara in the broader definition of <B>White<... Pin
Andreas Gieriet26-Feb-12 10:48
professionalAndreas Gieriet26-Feb-12 10:48 
I assist carrol_jhara in the broader definition of Whitespace. See also Wikipedia. Since C# strings are unicode, one can assume that anything manipulating Whitespaces respects the unicode definition of whitespace (26 different characters in total!).

Even Trim respects this, e.g:

<br />
<br />
 string s = "\n\f\r\t  a b c \u202F ";<br />
<br />
 Console.WriteLine("'{0}' <-- '{1}'", s.Trim(), s);<br />


results in:'a b c' <-- '
a b c ? '

And since Trim respects it, your example code is fine off! Wink | ;-)
GeneralReason for my vote of 2 will fail on whitespaces variants Pin
carrol_jhara12-Aug-10 18:46
carrol_jhara12-Aug-10 18:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.