Is use of string.IsNullOrEmpty(string)
when checking a string considered as bad practice when there is string.IsNullOrWhiteSpace(string)
in .NET 4.0 and above?
10 Answers
The best practice is selecting the most appropriate one.
.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.
The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.
Reference : Here
For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.
Reference : Here
Check the source code (Reference Source .NET Framework 4.6.2)
[Pure]
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
[Pure]
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;
}
Examples
string nullString = null;
string emptyString = "";
string whitespaceString = " ";
string nonEmptyString = "abc123";
bool result;
result = String.IsNullOrEmpty(nullString); // true
result = String.IsNullOrEmpty(emptyString); // true
result = String.IsNullOrEmpty(whitespaceString); // false
result = String.IsNullOrEmpty(nonEmptyString); // false
result = String.IsNullOrWhiteSpace(nullString); // true
result = String.IsNullOrWhiteSpace(emptyString); // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString); // false
-
Now I'm confused: "IsNullOrWhiteSpace is a convenience method that is similar to the following code, except that it offers superior performance" from here: msdn.microsoft.com/en-us/library/…– robastaCommented Feb 20, 2014 at 11:13
-
2@rob The code in question is
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
, which involves new string allocation and two separate checks. Most probably inside IsNullOrWhitespace it is done via single pass without any allocations by checking that each char in the string is the whitespace, hence superior performance. What confuses you actually? Commented Apr 11, 2014 at 9:21 -
17Thanks! I never knew if
IsNullOrWhitespace()
would match an empty string. In essenceIsNullOrEmpty()
matches a subset ofIsNullOrWhitespace()
.– gligoranCommented Feb 27, 2015 at 15:10
The differences in practice :
string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();
Result :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
**************************************************************
string testString = " MDS ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : False
**************************************************************
string testString = " ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : True
**************************************************************
string testString = string.Empty;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
**************************************************************
string testString = null;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
-
4This should be the accepted answer in my opinion. Makes more sense than the accepted answer with showing actual examples rather than a redirect.– eaglei22Commented May 9, 2016 at 20:46
-
@eaglei22 The accepted answer answers the question. This doesn't. Commented Sep 4, 2023 at 23:37
-
They are different functions. You should decide for your situation what do you need.
I don't consider using any of them as a bad practice. Most of the time IsNullOrEmpty()
is enough. But you have the choice :)
-
2For example, a user name field on a registration page would use IsNullOrEmtpy to validate so a user couldn't have a space as their name.– ChrisCommented Aug 7, 2011 at 23:51
-
15@Rfvgyhn: if you want to check that username doesn't have spaces anywhere - you should use
Contains
. If you want to ensure that username can't consist of spaces only -IsNullOrWhiteSpace
is ok.IsNullOrEmpty
ensures only that username was entered somehow. Commented Aug 7, 2011 at 23:53 -
1Indeed. I was just trying to give a concrete example to add to your answer. In the real world, a user name validation rule would usually contain a bit more logic than just checking if its empty or whitespace.– ChrisCommented Aug 8, 2011 at 2:22
-
Upvoted for actually answering the question, unlike so many of the "answers" here. Commented Sep 5, 2023 at 0:06
-
@Chris As Ivan pointed out, your "concrete example" is simply wrong --
!IsNullOrWhiteSpace(name)
doesn't prevent names from containing spaces. Commented Sep 5, 2023 at 0:08
Here is the actual implementation of both methods ( decompiled using dotPeek)
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsNullOrEmpty(string value)
{
if (value != null)
return value.Length == 0;
else
return true;
}
/// <summary>
/// Indicates whether a specified string is null, empty, or consists only of white-space characters.
/// </summary>
///
/// <returns>
/// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
/// </returns>
/// <param name="value">The string to test.</param>
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
-
4So this means
IsNullOrWhiteSpace
is true forstring.Empty
as well! That's a bonus :) Commented Aug 8, 2012 at 10:02 -
4yes , Safest will be to use IsNullOrWhiteSpace ( True for String.empty , null and whitespace )– akedCommented Jan 1, 2013 at 1:24
-
@ΕГИІИО It's not a "bonus", it's what the function is specified to do ... and it would be nuts for it to return true on " " but not "" -- the whole point is to determine whether the string contains non-space characters. Of course, the name is therefore misleading. Commented Sep 4, 2023 at 23:59
-
@JimBalter When you have two methods IsNullOrEmpty() & IsNullOrWhiteSpace(), I don't know about you, but for me the later means it should return false on "" :) Definitely not the best naming, I'll give you that. Commented Sep 5, 2023 at 9:11
-
The "meaning" of a method is determined by its specification, not its name. A method that returned true for null or " " but false for "" would be useless, so the specification is good but--as we agree--the name is poor. Commented Sep 5, 2023 at 9:14
It says it all IsNullOrEmpty()
does not include white spacing while IsNullOrWhiteSpace()
does!
IsNullOrEmpty()
If string is:
-Null
-Empty
IsNullOrWhiteSpace()
If string is:
-Null
-Empty
-Contains White Spaces Only
-
3I downvoted because while you explain what each function does, you don't answer the actual question. Commented Jan 20, 2014 at 16:34
-
3You should edit your answer to include the whole list for "white space", as defined by he framework: The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters.– georgerCommented Oct 17, 2016 at 13:24
-
@tuespetre That is distressingly common at SO, and most of the another "answers" on this page are the same. Commented Sep 4, 2023 at 23:54
Be careful of escaped characters:
String.IsNullOrEmpty(""); //True
String.IsNullOrEmpty(null); //True
String.IsNullOrEmpty(" "); //False
String.IsNullOrEmpty("\n"); //False
String.IsNullOrEmpty("\t"); //False
String.IsNullOrEmpty("hello"); //False
and here:
String.IsNullOrWhiteSpace("");//True
String.IsNullOrWhiteSpace(null);//True
String.IsNullOrWhiteSpace(" ");//True
String.IsNullOrWhiteSpace("\n");//True
String.IsNullOrWhiteSpace("\t");//True
String.IsNullOrWhiteSpace("hello");//False
If you apply Trim to the values passed to IsNullOrEmpty(), the results for the two methods will be the same.
As a matter of performance, IsNullOrWhiteSpace() would be faster.
Check this out with IsNullOrEmpty and IsNullOrwhiteSpace
string sTestes = "I like sweat peaches";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000000; i++)
{
for (int z = 0; z < 500; z++)
{
var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
}
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.ReadLine();
You'll see that IsNullOrWhiteSpace is much slower :/
-
1This is obvious because IsNullOrEmpty happens in constant time O(1)while IsNullOrwhiteSpace possibly requires a full iteration of the string or O(n) time. Then your timed example is actually using nearly O(n^2) time. For a one-timer with a normal-sized string, the performance difference is going to be negligible. If you were processing very large amounts of text or calling it in a large loop, then you probably wouldn't want to use it. Commented Nov 21, 2016 at 17:00
-
Of course it's slower, but that doesn't address the question. Commented Sep 4, 2023 at 23:39
-
@CharlesOwen "I like sweat peaches" is a "normal-sized" string, and the big-O of the function isn't changed by running it in a loop--that simply multiplies the times by a fixed factor (and irons out minor variations). If
IsNullOrWhiteSpace
is "much slower" then it is poorly implemented, since it should return false upon examining the first character ofsTestes
. A properly implemented version is O(s) where s is the number of initial spaces in the string. Commented Sep 4, 2023 at 23:47
In the .Net standard 2.0:
string.IsNullOrEmpty()
: Indicates whether the specified string is null or an Empty string.
Console.WriteLine(string.IsNullOrEmpty(null)); // True
Console.WriteLine(string.IsNullOrEmpty("")); // True
Console.WriteLine(string.IsNullOrEmpty(" ")); // False
Console.WriteLine(string.IsNullOrEmpty(" ")); // False
string.IsNullOrWhiteSpace()
: Indicates whether a specified string is null, empty, or consists only of white-space characters.
Console.WriteLine(string.IsNullOrWhiteSpace(null)); // True
Console.WriteLine(string.IsNullOrWhiteSpace("")); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
string.IsNullOrEmpty(str) - if you'd like to check string value has been provided
string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).
My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.
What about this for a catch all...
if (string.IsNullOrEmpty(x.Trim())
{
}
This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null.
I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something.
-
44This checking has a severe drawback. Calling Trim() on x will result a null reference exception when it is passed as null. Commented Nov 15, 2011 at 5:25
-
11Good point. Ill leave the answer incorrect to show the drawback.– RemotecCommented Dec 1, 2011 at 10:36
-
1IsNullOrWhitespace MAY optimise to check for null or empty, avoiding checking the string for white space. This method will always perform the trimming operation. Also, though it might be optimised away, it will probably create another string in memory.– SpragueCommented Jun 26, 2012 at 10:06
-
if (string.IsNullOrEmpty(x?.Trim()) should get around the null issue Commented Dec 21, 2017 at 0:38
-
I found exactly this bug in production code. In multiple places. It would be very funny if it weren't so sad.– radarbobCommented Sep 16, 2021 at 22:07