acadia
acadia

Reputation: 2621

Checking multiple conditions for a string in C#

I want to check multiple conditions in a string in C# but it throws error saying Cannot use && for string or boolean

if ((duStart.Trim() != "" && duStart.Trim() != null) &&(duEnd.Trim() != "" && duEnd.Trim() != null))
{
//do this
}
else
//do that

Upvotes: 0

Views: 1328

Answers (3)

HariM
HariM

Reputation: 1

Check for the Null first for duStart and duEnd. Then try Trim the string. Trim cannot be applied on a null value. So, below code block should work for you.

if ((duStart != null && duStart.Trim() != "") && (duEnd != null && duEnd.Trim() != ""))
{ 
   //do this 
}
else
{
   //do that 
}

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

you can simplify the condition by writing:

if( !string.IsNullOrEmpty(duStart.Trim()) && !string.isNullOrEmpty(duEnd.Trim()) )
{
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500805

The code you've given compiles fine. Here's a short but complete program - I've changed the whitespace of your line of code, but that's all:

using System;

class Test
{
    static void Main()
    {
        string duStart = "X";
        string duEnd = "X";
        if ((duStart.Trim() != "" && duStart.Trim() != null) &&
            (duEnd.Trim() != "" && duEnd.Trim() != null))
        {
            Console.WriteLine("Yes");
        }
    }
}

Having said that:

  • If you're going to use the same value (the trimmed version of duStart, for example) multiple times, there seems little point in computing it twice. I'd have used extra local variables (trimmedStart, trimmedEnd) here
  • Trim never returns null, so those tests are pointless.
  • Using string.IsNullOrWhitespace is probably a better idea here. Why bother creating strings that you're never going to use?

Upvotes: 2

Related Questions