cadena.IsNullOrEmpty(string) en comparación con la cadena.IsNullOrWhiteSpace (cadena)


¿El uso de string.IsNullOrEmpty(string) cuando se comprueba una cadena se considera una mala práctica cuando existe string.IsNullOrWhiteSpace(string) en. NET 4.0 y superior?

 180
Author: nawfal, 2011-08-08

8 answers

La mejor práctica es seleccionar la más adecuada.

. Net Framework 4.0 Beta 2 tiene un nuevo método IsNullOrWhiteSpace () para strings que generaliza el método IsNullOrEmpty () para incluir también otros espacio además de cadena vacía.

El término "espacio en blanco" incluye todos los caracteres que no son visibles en pantalla. Por ejemplo, el espacio, el salto de línea, la tabulación y la cadena vacía son blancos caracteres de espacio * .

Referencia : Aquí

Para el rendimiento, IsNullOrWhiteSpace no es ideal, pero es Bien. Las llamadas al método resultarán en una pequeña penalización de rendimiento. Además, el método isWhitespace en sí tiene algunas indirectas que pueden se eliminará si no está utilizando datos Unicode. Como siempre, prematuro la optimización puede ser mala, pero también es divertida.

Referencia : Aquí

Compruebe el código fuente (Fuente de referencia. 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;
}

Ejemplos

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
 288
Author: CharithJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 10:25:54

Las diferencias en la práctica:

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
 146
Author: Mohammad Dayyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-27 18:29:53

Son funciones diferentes. Usted debe decidir para su situación lo que necesita.

No considero que usar ninguno de ellos sea una mala práctica. La mayor parte del tiempo IsNullOrEmpty() es suficiente. Pero usted tiene la opción :)

 37
Author: Ivan Danilov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-07 23:47:32

Aquí está la implementación real de ambos métodos ( descompilados usando 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;
    }
 28
Author: dekdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-17 19:35:59

Lo dice todo IsNullOrEmpty() no incluye el espaciado en blanco mientras que IsNullOrWhiteSpace() lo hace!

IsNullOrEmpty() Si la cadena es:
- Null
- Vacío

IsNullOrWhiteSpace() Si la cadena es:
- Null
- Empty
- Contiene Solo Espacios En Blanco

 6
Author: Hk Shambesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 13:46:54

¿Qué hay de esto para un catch all...

if (string.IsNullOrEmpty(x.Trim())
{
}

Esto recortará todos los espacios si están allí evitando la penalización de rendimiento de isWhitespace, lo que permitirá que la cadena cumpla con la condición "vacía" si no es null.

También creo que esto es más claro y generalmente es una buena práctica recortar cadenas de todos modos, especialmente si las está poniendo en una base de datos o algo así.

 3
Author: Remotec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-11 15:56:49

Compruebe esto con IsNullOrEmpty e 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();

Verás que IsNullOrWhiteSpace es mucho más lento : /

 2
Author: user3852812,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-28 15:19:00

Cadena.IsNullOrEmpty (str) - si desea comprobar el valor de la cadena se ha proporcionado

Cadena.IsNullOrWhiteSpace (str) - básicamente esto ya es una especie de implementación de lógica de negocio (es decir, por qué "" es malo, pero algo como "~~" es bueno).

Mi consejo - no mezcle la lógica de negocios con comprobaciones técnicas. Así, por ejemplo, cadena.IsNullOrEmpty es el mejor para usar al principio de los métodos para verificar sus parámetros de entrada.

 0
Author: beloblotskiy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 22:53:34