473,581 Members | 2,605 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

validating a null string and an empty string in same IF statement?

VMI
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a Null
value. But I don't want to have two IFs (one that validates null and one
that validates an empty string). And I don't want to convert the null value
into a something that can be validated.

Any solution?

Thanks.
Nov 16 '05 #1
5 2444
VMI <vo******@yahoo .com> wrote:
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a Null
value. But I don't want to have two IFs (one that validates null and one
that validates an empty string). And I don't want to convert the null value
into a something that can be validated.


Do it the other way round:

if (myString==null || myString.Trim() .Length==0)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
VMI wrote:
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a Null
value. But I don't want to have two IFs (one that validates null and one
that validates an empty string). And I don't want to convert the null value
into a something that can be validated.

Any solution?


Put the null check first. If the string is null, the first check will
validate to true. Since you have an or condition, the second check for
length won't be executed if the first check validates to true.
--
Tom Porterfield
Nov 16 '05 #3
VMI
Thanks. It worked.
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
VMI <vo******@yahoo .com> wrote:
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a
Null
value. But I don't want to have two IFs (one that validates null and one
that validates an empty string). And I don't want to convert the null
value
into a something that can be validated.


Do it the other way round:

if (myString==null || myString.Trim() .Length==0)

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

Nov 16 '05 #4
It should also be noted that in .NET 2.0, the String class has a new
static method, IsNullOrEmpty, which can be used in this situation.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
VMI <vo******@yahoo .com> wrote:
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a
Null
value. But I don't want to have two IFs (one that validates null and one
that validates an empty string). And I don't want to convert the null
value
into a something that can be validated.


Do it the other way round:

if (myString==null || myString.Trim() .Length==0)

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

Nov 16 '05 #5
You may also want to do something like so as if Trim is what your after, you
only need to do it once using this method, then test it. Otherwise you
probably need to trim again after the test.
if ( s == null || ((string)(s = s.Trim())).Leng th == 0 )
{
Console.WriteLi ne("Null or empty.");
return;
}

--
William Stacey, MVP

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
VMI <vo******@yahoo .com> wrote:
How can I validate a null string or an empty string in the same IF
statement?
If I use this:

if (myString.Trim( ).Length <= 0 || myString == null)
{
//do stuff
}

I'll get a run-time error because I can't trim (or get the length) of a Null value. But I don't want to have two IFs (one that validates null and one that validates an empty string). And I don't want to convert the null value into a something that can be validated.


Do it the other way round:

if (myString==null || myString.Trim() .Length==0)

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


Nov 16 '05 #6

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

Similar topics

3
2111
by: iStrain | last post by:
Hiya. I'm _sure_ this is an FAQ, but Googling hasn't produced the answer in a way I can make sense out of. I know I should get this, but so far no way... I'm creating tables and doing queries in Perl, and Nulls have started to bother me greatly. The first issue is, as far as I understand it, a column should be NOT NULL if it is necessary...
7
5540
by: BlueDragon | last post by:
I don't know enough math to demonstrate that any numerical operation with a null should yield a null; although I would guess that it's true. I just don't buy it, however, when dealing with strings and nulls. In a simple table with first, middle and last name columns, I would infer that a null value in the middle name column means the HR person...
6
4318
by: TJS | last post by:
how to check for null attribute in form input field using IE this does not work in IE var curr_id = tablecells.getAttribute('name'); if (curr_id != null){ .... }
9
2009
by: D. Shane Fowlkes | last post by:
I'm using SQL Server 2000 and on my page, I'm simply creating a SQLDataReader and filling in Labels with the retrieved (single) record. However, how can I prevent from getting errors when a field is null? I've tried something like this (experimenting with IsDBNull): ========================================================= If...
5
2149
by: tshad | last post by:
I have the following code: *************************************************************************** Dim CommandText as String = "INSERT INTO ftsolutions.dbo.position (client,dateposted) VALUES ( @client,@dateposted)" Dim objCmd as New SqlCommand(CommandText,objConn) with objCmd.Parameters .Add("@client",SqlDbType.Char,50).value = "the...
7
12930
by: Tizzah | last post by:
What is wrong with that? regex = /^(http|https):\/\/+({1}+)*\.{2,5}(({1,5})?\/.*)?$/ if(field.hpage.value != regex.test(field.hpage.value)){ alert("Bad Homepage") field.hpage.focus() field.hpage.select() return false
23
7383
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion....
27
3106
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
232
13181
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an...
0
7873
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8153
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. ...
0
8178
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...
0
6558
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5679
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...
0
3806
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3830
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2304
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
0
1141
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...

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.