string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)
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)
IsNullorEmpty
[Pure]
public static bool IsNullOrEmpty(String value) {
return (value == null || value.Length == 0);
}
IsNullOrWhiteSpace
[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
Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#
- Source: MSDN
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 theChar.IsWhiteSpace
method as a
white-space character.
string.IsNullOrEmpty(myString.Trim()) vs string.IsNullOrWhiteSpace(myString)
string.IsNullOrEmpty(myString.Trim())
will throw exception if myString
is null
, whereas string.IsNullOrWhiteSpace(myString)
will work just fine, so it's more reliable.
As for the performance, string.IsNullOrWhiteSpace
should be faster.
string.IsNullOrWhiteSpace(myString)
is prefered way of checking if variable is empty or whitespace.
string.IsNullOrEmpty & string.IsNullOrWhiteSpace return false for empty string
As stated in my comment, in that screenshot you can see that trimmedSentence.Length
is 1, therefore it's not empty, and its contents is definitely not a standard space. If the string appears empty, it's because it has one of those so-called invisible characters. To check what your string has, you can directly access that character by doing trimmedSentence[0]
.
If that character will appear often, you might want to consider doing this:
string trimmedSentence = sentence.Trim().Replace("<this special character>", "");
Alternatively, you can create that replaceable string from the Unicode value by doing Char.ConvertFromUtf32(yourCharCode).ToString()
. You cannot use the Replace
overload that uses character parameters, as there is no "empty" character, only an empty string. You should be able to get this value while debugging. Or if necessary, by doing (int)trimmedSentence[0]
.
Java equivalent of c# String.IsNullOrEmpty() and String.IsNullOrWhiteSpace()
I would prefer not to use String.trim to check for existence of whitespace. It is doing more work than you need, since it checks both ends of the string (even if non-whitespace was found at the other end) AND it returns a new String object. So I would prefer to implement a method to check for whitespace only.
So my suggestion (if implementing yourself) would be as follows:
public static boolean isNullOrEmpty(String s) {
return s == null || s.length() == 0;
}
public static boolean isNullOrWhitespace(String s) {
return s == null || isWhitespace(s);
}
private static boolean isWhitespace(String s) {
int length = s.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
return false;
}
Or taking a cue from String.trim's implementation, you could use character comparison rather than Character.isWhitespace():
// checking for whitespace like String.trim() does
private static boolean isWhitespace(String s) {
int length = s.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
if (s.charAt(i) > ' ') {
return false;
}
}
return true;
}
return false;
}
Finally, I'd consider checking both ends of the string in each iteration, stepping inwards. This would minimize the number of iterations needed to get the answer, regardless of whether whitespace exists at the front or the end of the string.
private static boolean isWhitespace(String s) {
int length = s.length();
if (length > 0) {
for (int start = 0, middle = length / 2, end = length - 1; start <= middle; start++, end--) {
if (s.charAt(start) > ' ' || s.charAt(end) > ' ') {
return false;
}
}
return true;
}
return false;
}
string.IsNullOrEmpty(myString) or string.IsNullOrWhiteSpace(myString) is not violating SRP Rule?
The SRP says that a function or class should have only one reason to change. What is a reason to change? A reason to change is a user who requests changes. So a class or function should have only one user who requests changes.
Now a function that does some calculations and then some formatting, has two different users that could request a change. One would request changes to the calculations and the other would request changes to the formatting. Since these users have different needs and will make their requests and different times, we'd like them to be served by different functions.
IsNullOrEmpty(String) is not likely to be serving two different users. The user who cares about null is likely the same user who cares about empty, so isNullOrEmpty does not violate the SRP.
string.IsNullOrEmpty() vs string.NotNullOrEmpty()
Because "IsNullOrEmpty" is easier to understand than "NotNullOrEmpty". The latter could be interpreted as:
- It's not null and it's not empty
- It's not null or it is empty
String.IsNullOrEmpty or string.IsNullOrEmpty
They are both the same.
string is a keyword alias in c# for System.String.
Only difference is that when using String, you need to use either System.String.IsNullOrEmpty
or using System;
at the begining of your code file.
Related Topics
Add Two Lists of Different Length in C#
Creating Diagonal Pattern in Wpf
How to Deserialize Xml If the Return Type Could Be an Error or Success Object
What Does Default(Object); Do in C#
Async Call with Await in Httpclient Never Returns
Fields of Class, Are They Stored in the Stack or Heap
Possible to Use Automapper to Map One Object to List of Objects
A Type for Date Only in C# - Why Is There No Date Type
System.Web.Httpcontext.Current.User.Identity.Name VS System.Environment.Username in ASP.NET
Extremely Large Single-Line File Parse
How to Convert Securestring to System.String
Using Lambda Expressions for Event Handlers
Binding Objects Defined in Code-Behind
My C# Application Is Returning 0Xe0434352 to Windows Task Scheduler But It Is Not Crashing