5 Wrong ways to check empty strings 5 Неправильний шлях перевірити порожніми рядками
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. Вона є однією з загальних помилки, які люди порівняти рядок з "" або String.Empty в VB.Net или C #, щоб знайти його порожнім. Here are few examples. Ось кілька прикладів.
// C# Wrong Ways / / C # Невірний Шляхи
- if ( s == “” ) якщо (S == "")
- if ( s == string.Empty ) якщо (S == string.Empty)
- if ( s.Equals(””) ) якщо (s.Equals ( ""))
- if ( s.Equals ( String.Empty) якщо (s.Equals (String.Empty)
- if ( string.Equals(s,””) якщо (string.Equals (S, "")
- if ( string.Equals ( s,String.Empty )) якщо (string.Equals (S, String.Empty))
So what's the correct way to do it ? Так що, як правильно це зробити? Check for length too. Перевірити довжину теж.
// [ C# ] Correct Way / / [C #] Правильний шлях
if ( s.Length == 0 ) якщо (s.Length == 0)
This is in continuation of our last post on Це в продовження нашої останнього на пост Check for length too when you check for null strings in VB.Net and C# Перевірити довжину теж коли ви перевіряєте на нуль рядків у VB.Net і C #
Read below for the right approach. Читайте нижче, правильний підхід.

Posted on 6th April 2008 by Опубліковано 6 квітня 2008 року Ashish Mohta Ashish Mohta , A tech blogger who writes about solving day to day problems of people who use computer. , А тек блогери, який пише про вирішення повсякденних проблем людей, які використовують комп'ютер. He also writes on How to use the applications like Office, PC tips, Online tools,Browsers and more. All posts by Він також пише про те, як використовувати у програмах, як управління, PC поради, онлайн інструменти, браузери та багато чого іншого. Всі посади Ashish Mohta Ashish Mohta | Connect with me @ | Зв'язатися зі мною @ Twitter Щебетати | | Linkedin LinkedIn | | Facebook Facebook | | Stumble Stumble | Need more help? | Потрібна допомога? Ask your Questions at our Задайте свої питання на нашому Support Center Центр підтримки




























Free Email Subscription
If you look at the disassembly of string.IsNullOrEmpty you will see what it does. Якщо ви подивитеся на розбирання string.IsNullOrEmpty ви побачите, що вона робить.
.method public hidebysig static bool IsNullOrEmpty(string 'value') cil managed . Методі громадських hidebysig статичних BOOL IsNullOrEmpty (рядок 'значення') КСС вдалося
{ (
.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 інстанції 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: у відставці
L_000d: ldc.i4.1 L_000d: ldc.i4.1
L_000e: ret L_000e: у відставці
} )
This translates to (C#): Це призводить до (C #):
public static bool IsNullOrEmpty(string value) громадськості статичної BOOL IsNullOrEmpty (рядкові значення)
{ (
if (value != null) якщо (значення! = NULL)
{ (
return (value.Length == 0); повернення (value.Length == 0);
} )
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. Тепер Ви можете виконати цю дію на свій власний, то все и дело платформи. NET Framework є той факт, що це вдалося код. 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. Якщо з якихось причин Microsoft вирішить змінити здійснення рядок класу такі, що є ще один випадок, коли вона порожня, вона призведе до зміни її здійсненню тут. And you would never have to worry about your code breaking due to an underlying change. І ви ніколи не доведеться турбуватися про ваш код розірвати зв'язку з основоположних змін.
So, in short, use string.IsNullOrEmpty(). Отже, коротше кажучи, використовувати string.IsNullOrEmpty ().