开发者

Checking multiple conditions for a string in C#

开发者 https://www.devze.com 2023-02-03 06:49 出处:网络
I want to check multiple conditions in a string in C#开发者_如何学运维 but it throws error saying Cannot use && for string or boolean

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:

  • 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?


you can simplify the condition by writing:

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


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 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号