Have there any function to check the null and empty at once

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I have a string like string sNo.
I want to cast it to int with int.Parse(sNo)
but if the string is null or empty, it will thow exception.

I must check if sNo is not null and is not empty before cast like:
if ((sNo<>null) && (sNo<>""))

Have there any function to check the null and "" at once
 
ad said:
I have a string like string sNo.
I want to cast it to int with int.Parse(sNo)
but if the string is null or empty, it will thow exception.

I must check if sNo is not null and is not empty before cast like:
if ((sNo<>null) && (sNo<>""))

Have there any function to check the null and "" at once

Prior to .NET 2.0, you must provide your own solution.
In .NET 2.0, there's String.IsNullOrEmpty().

Cheers,
 
ad said:
I have a string like string sNo.
I want to cast it to int with int.Parse(sNo)
but if the string is null or empty, it will thow exception.

I must check if sNo is not null and is not empty before cast like:
if ((sNo<>null) && (sNo<>""))

Have there any function to check the null and "" at once

Well, first of all, it's
if ((sNo != null) && (sNo != "")

as <> is a syntax error. Also, there's not much sense is checking if a
string is less than "", since it can't be. I prefer
if ( sNo != null && sNo.Length > 0)
but that's just me.

As Joerg pointed out, in .Net 2.0 is could use:
if (String.IsNullOrEmpty(sNo))
But, let's no much less typing what you've got now. Ultimately, the problem
is that we really want to write :

if (sNo.IsNullorEmpty())

but there is no way to get that to work is sNo is null.
 
Back
Top