Question

What are differences between these commands in C#

string text= "  ";
1-string.IsNullOrEmpty(text.Trim())

2-string.IsNullOrWhiteSpace(text)
Was it helpful?

Solution

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.

OTHER TIPS

Short answer:

In common use, space " ", Tab "\t" and newline "\n" are the difference:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

also see this answer about: whitespace characters


Long answer:

There are also a few other white space characters, you probably never used before

  • Members of the UnicodeCategory.SpaceSeparator category, which includes the characters SPACE (U+0020), NO-BREAK SPACE (U+00A0), OGHAM SPACE MARK (U+1680), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).
  • Members of the UnicodeCategory.LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).
  • Members of the UnicodeCategory.ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029).
  • The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), and NEXT LINE (U+0085).

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

The first method checks if a string is null or a blank string. In your example you can risk a null reference since you are not checking for null before trimming

1- string.IsNullOrEmpty(text.Trim())

The second method checks if a string is null or an arbitrary number of spaces in the string (including a blank string)

2- string .IsNullOrWhiteSpace(text)

The method IsNullOrWhiteSpace covers IsNullOrEmpty, but it also returns true if the string contains only white space characters.

In your concrete example you should use 2) as you run the risk of a null reference exception in approach 1) since you're calling trim on a string that may be null

String.IsNullOrEmpty(string value) returns true if the string is null or empty. For reference an empty string is represented by "" (two double quote characters)

String.IsNullOrWhitespace(string value) returns true if the string is null, empty, or contains only whitespace characters such as a space or tab.

To see what characters count as whitespace consult this link: http://msdn.microsoft.com/en-us/library/t809ektx.aspx

This is implementation of methods after decompiling.

    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;
    }

So it is obvious that IsNullOrWhiteSpace method also checks if value that is being passed contain white spaces.

Whitespaces refer : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx

If your string (In your case the variable text) could be null this would make a big Difference:

1-string.IsNullOrEmpty(text.Trim()) --> EXCEPTION since your calling a mthode of a null object

2-string.IsNullOrWhiteSpace(text) This would work fine since the null issue is beeing checked internally

To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method

if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }

String.IsNullOrWhiteSpace(text) should be used in most cases as it also includes a blank strings with whitespaces but no other text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";
            
            Console.WriteLine(string.IsNullOrWhiteSpace(str));              
            
        }
    }
}

It returns True!

[Performance Test] just in case anyone is wondering, in a stopwatch test comparing

if(nopass.Trim().Length > 0)

if (!string.IsNullOrWhiteSpace(nopass))



these were the results:

Trim-Length with empty value = 15

Trim-Length with not empty value = 52


IsNullOrWhiteSpace with empty value = 11

IsNullOrWhiteSpace with not empty value = 12

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top