0

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
2
  • 2
    Trim() cannot return null. Look at the String.IsNullOrWhiteSpace() method. Commented Jan 10, 2011 at 20:12
  • 1
    The code you have posted compiles. The error is somewhere else. Please post the relevant part of your code. Commented Jan 10, 2011 at 20:13

3 Answers 3

2

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?
Sign up to request clarification or add additional context in comments.

2 Comments

Btw the strange null check could mean that the originals duStart and duEnd could be null, if this is the case a check has to be done before
@Felice: Nope, because then calling duStart.Trim() would throw an exception to start with, wouldn't it?
1

you can simplify the condition by writing:

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

1 Comment

Better to use the suggestion of SLaks, IsNullOrWhiteSpace, and avoid using Trim at all.
0

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 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.