Home Home page » » Dot Net Punto Net

5 Wrong ways to check empty strings 5 modi per errato controllo stringhe vuote

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. Si tratta di uno dei errore comune che le persone confrontare una stringa con "" o String.Empty VB.Net in C # o di trovare il proprio vuoto. Here are few examples. Ecco alcuni esempi.

// C# Wrong Ways / / C # errata Modi

  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 ? Che cosa è il modo corretto di farlo? Check for length too. Verificare la presenza di lunghezza troppo.

// [ C# ] Correct Way / / [C #] modo corretto

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

This is in continuation of our last post on Questo è in continuazione del nostro ultimo post sul Check for length too when you check for null strings in VB.Net and C# Verificare la presenza di lunghezza troppo quando si verifica per nulla stringhe in VB.Net e C #

Read below for the right approach. Leggi di seguito per l'approccio giusto.

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

    I agree with Shahar. Sono d'accordo con Shahar. string.IsNullOrEmpty is the best, managed way to test. string.IsNullOrEmpty è il migliore, gestito modo di testare. It’s static and guaranteed not to throw a NullReferenceException. E 'statica e garantito di non gettare uno NullReferenceException. You can’t say that about .Length. Non si può dire che circa. Lunghezza.

    If you look at the disassembly of string.IsNullOrEmpty you will see what it does. Se guardate il disassemblaggio del string.IsNullOrEmpty vedrete ciò che fa.
    .method public hidebysig static bool IsNullOrEmpty(string ‘value’) cil managed . hidebysig metodo statico pubblico bool IsNullOrEmpty (stringa 'valore') CIL gestito
    { (
    .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 esempio 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#): Ciò si traduce a (C #):
    public static bool IsNullOrEmpty(string value) public static bool IsNullOrEmpty (valore stringa)
    { (
    if (value != null) if (valore! = 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. Ora, mentre è possibile eseguire questa operazione sul proprio, l'intero punto di. NET Framework è il fatto che si tratta di codice gestito. 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. Se per qualche motivo, Microsoft decide di cambiare l'attuazione della stringa di classe in modo che vi sia un altro caso in cui esso è vuoto, sarebbe cambiare la sua attuazione qui. And you would never have to worry about your code breaking due to an underlying change. E voi non avrebbe mai preoccuparsi di rompere il codice a causa di un cambiamento di base.

    So, in short, use string.IsNullOrEmpty(). Quindi, in breve, l'uso string.IsNullOrEmpty ().

Tags: Tag: ,

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
SMS abbonarsiPrint This Post

Posted on 6th April 2008 by Pubblicato il 6 aprile 2008 Ashish Mohta Ashish Mohta , A tech blogger who writes about solving day to day problems of people who use computer. , Una tecnologia blogger che scrive circa la risoluzione di giorno in giorno i problemi delle persone che usano i computer. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more. All posts by Egli scrive anche su come utilizzare le applicazioni di Office come, PC suggerimenti, strumenti on-line, browser e molto altro ancora. Tutti i posti da Ashish Mohta Ashish Mohta | Connect with me @ | Collegare con me @ Twitter Twitter | | Linkedin LinkedIn | | Facebook Facebook | | Stumble Stumble | Need more help? | Serve ulteriore aiuto? Ask your Questions at our Le vostre domande al nostro Support Center Support Center

Thanksgiving Special !!! Ringraziamento speciale!

Leave your response! Lascia la tua risposta!

Be nice. Sii gentile. Keep it clean. Tenere pulito. Stay on topic. Rimani in argomento. No spam. N. spam.

You can use these tags: È possibile utilizzare questi tag:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>