Home Início » » Dot Net Dot Net

5 Wrong ways to check empty strings Errado 5 maneiras de verificar strings vazias

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. É um erro comum das pessoas que comparar uma seqüência com "" ou String.Empty em C # ou VB.Net para encontrar o seu vazio. Here are few examples. Aqui estão alguns exemplos.

// 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 ? Então, qual é a forma correta de fazê-lo? Check for length too. Verifique se há demasiado tempo.

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

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

This is in continuation of our last post on Esta é uma continuação do nosso último post sobre Check for length too when you check for null strings in VB.Net and C# Verifique se há demasiado tempo quando se verificar a existência de nulidade na seqüências VB.Net e C #

Read below for the right approach. Leia a seguir para a abordagem certa.

  • Ryan Heaney Ryan Heaney , March 27, 2008: , 27 de março de 2008:

    I agree with Shahar. Concordo com Shahar. string.IsNullOrEmpty is the best, managed way to test. string.IsNullOrEmpty é o melhor, gerido forma de teste. It’s static and guaranteed not to throw a NullReferenceException. É estática e não garante que jogar um NullReferenceException. You can’t say that about .Length. Você não pode dizer que cerca. Length.

    If you look at the disassembly of string.IsNullOrEmpty you will see what it does. Se você olhar para a desmontagem de string.IsNullOrEmpty você vai ver o que ela faz.
    .method public hidebysig static bool IsNullOrEmpty(string ‘value’) cil managed . hidebysig método público estático bool IsNullOrEmpty (string 'valor') cil geridas
    { (
    .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 exemplo 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#): Isto traduz a (C #):
    public static bool IsNullOrEmpty(string value) bool IsNullOrEmpty público estático (string valor)
    { (
    if (value != null) if (valor! = null)
    { (
    return (value.Length == 0); retorno (value.Length == 0);
    } )
    return true; retornar 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. Agora, embora você possa executar esta operação no seu próprio, a totalidade do ponto. NET Framework é o fato de que esse é o código gerenciado. 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 por algum motivo a Microsoft decide mudar a implementação da seqüência dessa classe que existe um outro caso em que ela estiver vazia, ela iria mudar a sua implementação aqui. And you would never have to worry about your code breaking due to an underlying change. E você nunca teria de se preocupar com o seu código quebrar devido a uma mudança subjacente.

    So, in short, use string.IsNullOrEmpty(). Assim, em breve, usar 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
SMS subscreverPrint This Post

Posted on 6th April 2008 by Postado em 6 de abril de 2008 Ashish Mohta Ashish Mohta , A tech blogger who writes about solving day to day problems of people who use computer. , A tecnologia blogueiro que escreve sobre resolver problemas do dia a dia das pessoas que usam o computador. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more. All posts by Ele também escreve sobre "Como gosto de usar as aplicações do Office, PC dicas, ferramentas online, navegadores e muito mais. Todas as postagens de Ashish Mohta Ashish Mohta | Connect with me @ | Ligue-se a mim @ Twitter Twitter | | Linkedin Linkedin | | Facebook Facebook | | Stumble Tropeçar | Need more help? | Necessita de mais ajuda? Ask your Questions at our Faça perguntas à nossa Support Center Support Center




Leave your response! Deixe sua resposta!

Be nice. Seja simpático. Keep it clean. Mantenha-o limpo. Stay on topic. Permaneça no tópico. No spam. Nenhum spam.

You can use these tags: Você pode usar estas tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>