Home Accueil » » Dot Net Dot Net

5 Wrong ways to check empty strings 5 Wrong les moyens de vérifier les chaînes vides

It is one of the common mistake that people compare a string with “” or String.Empty in VB.Net or C# to find its empty. Il est l'un de l'erreur commune que les gens de comparer une chaîne avec "" ou String.Empty en VB.Net ou C # pour trouver son vide. Here are few examples. Voici quelques exemples.

// C# Wrong Ways / / C # Wrong Ways

  1. if ( s == “” ) if (s == "")
  2. if ( s == string.Empty ) if (s == string.Empty)
  3. if ( s.Equals(””) ) if (s.Equals ( ""))
  4. if ( s.Equals ( String.Empty) if (s.Equals (String.Empty)
  5. if ( string.Equals(s,””) if (string.Equals (s, "")
  6. if ( string.Equals ( s,String.Empty )) if (string.Equals (s, String.Empty))

So what’s the correct way to do it ? Alors, quel est la bonne façon de le faire? Check for length too. Vérifier la longueur de trop.

// [ C# ] Correct Way / / [C #] correcte

if ( s.Length == 0 ) if (s.Length == 0)

This is in continuation of our last post on C'est dans le prolongement de notre dernier post sur Check for length too when you check for null strings in VB.Net and C# Vérifier la longueur de trop lorsque vous vérifiez la valeur NULL dans les chaînes de VB.Net et C #

Read below for the right approach. Lire ci-dessous pour la bonne approche.

  • Ryan Heaney Ryan Heaney , March 27, 2008: 27 Mars 2008:

    I agree with Shahar. Je suis d'accord avec Shahar. string.IsNullOrEmpty is the best, managed way to test. string.IsNullOrEmpty est le meilleur, géré moyen de tester. It’s static and guaranteed not to throw a NullReferenceException. Il est statique et la garantie de ne pas jeter un NullReferenceException. You can’t say that about .Length. Vous ne pouvez pas dire que sur. Longueur.

    If you look at the disassembly of string.IsNullOrEmpty you will see what it does. Si vous regardez le démontage du string.IsNullOrEmpty vous verrez ce qu'il fait.
    .method public hidebysig static bool IsNullOrEmpty(string ‘value’) cil managed . hidebysig méthode public static bool IsNullOrEmpty (chaîne de caractères' valeur ') géré CIL
    { (
    .maxstack 8 . maxstack 8
    L_0000: ldarg.0 L_0000: ldarg.0
    L_0001: brfalse.s L_000d L_0001: brfalse.s L_000d
    L_0003: ldarg.0 L_0003: ldarg.0
    L_0004: callvirt instance int32 System.String::get_Length() L_0004: callvirt exemple int32 System.String:: get_Length ()
    L_0009: ldc.i4.0 L_0009: ldc.i4.0
    L_000a: ceq L_000a: CEQ
    L_000c: ret L_000c: ret
    L_000d: ldc.i4.1 L_000d: ldc.i4.1
    L_000e: ret L_000e: ret
    } )

    This translates to (C#): Cela se traduit par (C #):
    public static bool IsNullOrEmpty(string value) public static bool IsNullOrEmpty (valeur de chaîne)
    { (
    if (value != null) if (value! = null)
    { (
    return (value.Length == 0); return (value.Length == 0);
    } )
    return true; return true;
    } )

    Now while you can perform this operation on your own, the whole point of the .NET Framework is the fact that this is managed code. Maintenant, alors que vous pouvez effectuer cette opération sur votre propre, l'ensemble du point de l'. NET Framework est le fait que ce code est géré. If for some reason Microsoft decides to change the implementation of the string class such that there is another case in which it is empty, it would change its implementation here. Si pour une raison quelconque, Microsoft décide de changer la mise en oeuvre de la chaîne de telle sorte que la classe il ya un autre cas dans lequel il est vide, il allait changer sa mise en œuvre ici. And you would never have to worry about your code breaking due to an underlying change. Et vous n'auriez jamais à vous soucier de votre code de rupture en raison d'un changement qui sous-tendent.

    So, in short, use string.IsNullOrEmpty(). Donc, en bref, utiliser string.IsNullOrEmpty ().

Tags: ,

Translate to EnglishÜbersetzen Sie zum Deutsch/GermanПереведите к русскому/RussianΜεταφράστε στα ελληνικά/GreekVertaal aan het Nederlands/Dutchترجمة الى العربية/Arabic中文翻译/Chinese Traditional中文翻译/Chinese Simplified한국어에게 번역하십시오/Korean日本語に翻訳しなさい /JapaneseTraduza ao Português/PortugueseTraduca ad Italiano/ItalianTraduisez au Français/FrenchTraduzca al Español/Spanish
Abonnez-SMSPrint This Post

Posted on 6th April 2008 by Posté le 6 avril 2008 par Ashish Mohta Ashish Mohta , A tech blogger who writes about solving day to day problems of people who use computer. , Une technologie blogueur qui écrit sur la résolution au jour le jour les problèmes de personnes qui utilisent l'ordinateur. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more. All posts by Il a également écrit sur la façon d'utiliser les applications comme Office, PC des conseils, des outils en ligne, les navigateurs et plus. Tous les postes de Ashish Mohta Ashish Mohta | Connect with me @ | Connectez-vous avec moi @ Twitter Twitter | | Linkedin LinkedIn | | Facebook Facebook | | Stumble Stumble | Need more help? | Besoin d'aide? Ask your Questions at our Posez vos questions à notre Support Center Support Center

Thanksgiving Special !!! Spécial de grâce!

Leave your response! Laissez votre réponse!

Be nice. Soyez gentil. Keep it clean. Gardez-le propre. Stay on topic. Restez sur le sujet. No spam. Pas de spam.

You can use these tags: Vous pouvez utiliser ces tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>