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

V

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.
 
J

Jon Skeet [C# MVP]

VMI said:
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)
 
T

Tom Porterfield

VMI said:
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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
W

William Stacey [MVP]

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())).Length == 0 )
{
Console.WriteLine("Null or empty.");
return;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top