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
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:
duStart, for example) multiple times, there seems little point in computing it twice. I'd have used extra local variables (trimmedStart, trimmedEnd) hereTrim never returns null, so those tests are pointless.string.IsNullOrWhitespace is probably a better idea here. Why bother creating strings that you're never going to use?duStart.Trim() would throw an exception to start with, wouldn't it?you can simplify the condition by writing:
if( !string.IsNullOrEmpty(duStart.Trim()) && !string.isNullOrEmpty(duEnd.Trim()) )
{
}
Trim()cannot returnnull. Look at theString.IsNullOrWhiteSpace()method.