473,699 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

.text == "" vs .length==0

I am trying to learn the best ways to do some things in c#

When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0

and why would I use one over the other. And if it doesn't matter,
just let me know that also.

Thanks
Nov 15 '05 #1
13 1921
"j_ruez" <j_****@yahoo.c om> wrote in message
news:17******** *************** ***@posting.goo gle.com...
When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0


A more descriptive, and potentially platform-safe way could be this:

txtValue.Text == string.Empty

However, bear in mind that strings can also be null, so you may want to
check this also!

Tobin
Nov 15 '05 #2
j_ruez,

I personally would use the following when working with strings in
general:

if (pstrString == null || pstrString.Leng th == 0)
// Perform operation here.

The reason for this is that you are not guaranteed to always hold a
reference to the string. Now your logic for what to do with a null
reference might be different than others, but you should take it into
consideration.

Also, the TextBox class might always return an empty string, in which
case, I would just check the length (it should be quicker than checking
against the empty string, which you should use "String.Emp ty" for as well).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- nick(dot)paldin o=at=exisconsul ting<dot>com

"j_ruez" <j_****@yahoo.c om> wrote in message
news:17******** *************** ***@posting.goo gle.com...
I am trying to learn the best ways to do some things in c#

When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0

and why would I use one over the other. And if it doesn't matter,
just let me know that also.

Thanks

Nov 15 '05 #3
The most performant way is to check for Length == 0.

--
Mickey Williams
Author, "Microsoft Visual C# .NET Core Reference", MS Press
www.servergeek.com
"Tobin Harris" <co**********@h otmail.com> wrote in message
news:bl******** ****@ID-135366.news.uni-berlin.de...
"j_ruez" <j_****@yahoo.c om> wrote in message
news:17******** *************** ***@posting.goo gle.com...
When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0


A more descriptive, and potentially platform-safe way could be this:

txtValue.Text == string.Empty

However, bear in mind that strings can also be null, so you may want to
check this also!

Tobin

Nov 15 '05 #4
Tobin Harris <co**********@h otmail.com> wrote:
A more descriptive, and potentially platform-safe way could be this:

txtValue.Text == string.Empty
I don't see how it would ever be more platform-safe. As for descriptive
- I think on this one it's a matter of preference. I'd probably use
=="" myself, but that's not to say that using String.Empty isn't just
as good.
However, bear in mind that strings can also be null, so you may want to
check this also!


That's very true.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
j_****@yahoo.co m (j_ruez) wrote in
news:17******** *************** ***@posting.goo gle.com:
I am trying to learn the best ways to do some things in c#

When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0

and why would I use one over the other. And if it doesn't matter,
just let me know that also.


Both ways are OK. To build on Tobin's answer, you can use a small
utility method to make testing for an empty or null string easier:

public sealed class StringUtilities
{
public static bool IsStringEmpty(
string s)
{
return (s == null) || (s.Length == 0);
}
}

You may also consider a string that contains only whitespace to be
"empty". In that case, the Trim() method can be used to strip
leading and trailing whitespace from the string before the Length
test is done:

public sealed class StringUtilities
{
public static bool IsStringEmpty(
string s)
{
return (s == null) || (s.Trim().Lengt h == 0);
}
}
Hope this helps.

Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/
Nov 15 '05 #6
Although I haven't verified this, my assumption would be that if you used
the - txtValue.Text == "" method to test if a string was empty, then an
extra string object would have to be created at run-time (for the "").
Although this probably isn't that big of an issue, I suppose it could be if
it were implemented within a large loop.

Using the - txtValue.Length == 0 way shouldn't have to create the extra
string object.

Just my $0.02 worth.

--- Jeff

"j_ruez" <j_****@yahoo.c om> wrote in message
news:17******** *************** ***@posting.goo gle.com...
I am trying to learn the best ways to do some things in c#

When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0

and why would I use one over the other. And if it doesn't matter,
just let me know that also.

Thanks

Nov 15 '05 #7
Jeff <je**@nowhere.c om> wrote:
Although I haven't verified this, my assumption would be that if you used
the - txtValue.Text == "" method to test if a string was empty, then an
extra string object would have to be created at run-time (for the "").


No. String literals are interned when classes are loaded. In other
words, "" is a reference to the same string wherever it's used.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
Jon,

Thanks for the clarification.

--- Jeff

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Jeff <je**@nowhere.c om> wrote:
Although I haven't verified this, my assumption would be that if you used the - txtValue.Text == "" method to test if a string was empty, then an
extra string object would have to be created at run-time (for the "").


No. String literals are interned when classes are loaded. In other
words, "" is a reference to the same string wherever it's used.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #9
j_ruez wrote:
I am trying to learn the best ways to do some things in c#

When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue

Should I use

txtValue.Text == ""

or

txtValue.Length == 0

and why would I use one over the other. And if it doesn't matter,
just let me know that also.

Thanks


Let's look at the IL:

(txtValue.Text == "") boils down to a call to String.op_Equal ity(),
which in turn calls String.Equals( string, string). This checks for
reference equality and does some checks for null parameters before
calling String.Equals( string), which is implemented in native code, not
IL, and ILDASM won't tell me what's in there. I decided I didn't need to
go any further (farther?). I'll assume that the first thing
String.Equals does is check for the lengths being the same; actually it
probably checks for reference equality and/or a null parameter first.

(txtValue.Lengt h == 0) boils down to a call to
String.get_Leng th(), followed by a test for 0 (generally a 'brtrue' IL
instruction).

So, the second idiom is certainly more efficient in terms of IL - but,
we're looking at IL which may well be JIT'ed to some very efficient code
(in both cases), since the String class is sealed.

My opinion (for what it's worth) is to use whichever idiom seems most
readable to you, which may well be different in different areas of code.
I think the real-world speed difference will never be noticed (or even
measurable) in code that's doing any real work with strings.

Also, I'd suggest not using String.Empty (which I've seen in other
responses) - it buys you nothing, and I find it to be far less readable
than the simple, natural, well-used "".

--
mikeb

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1924
by: Jukka K. Korpela | last post by:
No, I'm not making this up, this is what http://www.w3.org/ says when accessed with a text browser, or in any decent browser in no-images mode: "Tim Berners-Lee smiling 2003-12-31: Buckingham Palace today announced that Queen Elizabeth II will make Tim Berners-Lee, W3C Director, a Knight Commander of the Order of the British Empire (KBE)." Actually, I could see the point of title="Tim Berners-Lee smiling", since it's not obvious to...
4
9897
by: moondaddy | last post by:
Is there a asp.net validator control that validates the length of the text being entered or does everyone just write jscript for this? -- moondaddy@nospam.com
5
2180
by: Kivak Wolf | last post by:
Hey everyone, I have a textbox in my web page that is going to be used to enter an E-mail into (just plain text, no HTML). Now, this will interact with a SQL database where the contents of the textbox are sent from the SQL database to the textbox, then the user edits it, and then the text inside the textbox is sent back to the SQL database. I did it the same way as if i had used a VarChar instead of a type "text" variable in the SQL...
1
3517
by: Linda | last post by:
Hi, Is there a way to do a "text" (rather than "binary") compareison with the "like" operator, without changing the global "Option Compare" setting? I don't want to risk breaking many, many lines of functional code just to get one "like" operation to behave as I wish. I want to check whether a single-character string is (a letter or number, INCLUDING diacritical letters) or whether it is (something else.)
2
3788
by: gabon | last post by:
I'm creating a select entirely through JavaScript and very strangely IE doesn't show the text in the option elements. Here part of the code: this.form_country=document.createElement("select"); var option; for(var i=0; i<arr.length; i++){ option=document.createElement("option"); option.value=arr.code;
1
2805
by: bbcdancer | last post by:
Is it possible to restrict the length of a text box in MS Access using VBA on condition to what is selected in a list combo box. Scenario: 1. I have a list combo box containing: AA BBB CCCC
1
4929
by: Arielle | last post by:
I'm trying to save a memo to a database.. Right now it's declared as "text" what's the max size of that?
0
2470
by: mervyn | last post by:
Hi There, I am very new to .NET and VB so this may be a really simple thing to solve but here is my issue I have a a textbox with a value in it. I know what the length of the text in the text box is. I would then like to set the width of the text box (in px) to an appropriate calculated value based on the length. So, if the text length is 50, I would need a text box of around 300px for the text to be shown without being truncated. Is there...
40
4654
by: blad3runn69 | last post by:
hi, just wondering how you good peoples get around combobox width and text length, in the context of making it easy for the user to read a long string? like this example Thanks for your help it is always greatly appreciated.
0
9178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8916
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8885
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.