开发者

C# Help with OR checking both sides

开发者 https://www.devze.com 2023-02-26 21:32 出处:网络
This should be an easy question hopefully but as a rookie I don\'t know the answer. In the code below if ignorePath is true I don\'t want to e开发者_C百科nter the if statement even if tempPath is not

This should be an easy question hopefully but as a rookie I don't know the answer.

In the code below if ignorePath is true I don't want to e开发者_C百科nter the if statement even if tempPath is not null and tempPath length is not 0. I thought a single | would do this but it appears not to.

if (((tempPath != null) && (tempPath.Length != 0)) | ignorePath == false)
{

}

Thanks


I'd say the following code would be clearer:

if ((!ignorePath) && (tempPath != null) && (tempPath.Length != 0))
{
    // do something here
}

First you verify that ignorePath is false (because you don't want the code to execute when it is true), then you check that tempPath is not null and that its length is non-zero.

The advantage here is that you've moved the check of the ignorePath variable to be first. Since it is apparently the most important thing to you (it overrides the other two conditions), it ought to come first for clarity and readability (and performance, I suppose, but that hardly matters here).


Remember that there's no reason to check Boolean types against the literal values true or false. An if statement already evaluates whether the value of the statement inside the ( ) is true or false. Specifying it explicitly is just redundant.

The only problem I see with the above code is that !ignorePath is a little difficult to read. It creates a double negative, as you're "not-ignoring" something. What exactly does that mean? That's why most coding standards (including Microsoft's recommended standards for .NET) encourage you to name Boolean variables with positive grammar. I'd call that variable something like checkPath, instead.


if (!ignorePath || ((tempPath != null) && (tempPath.Length != 0)))


So, if I understand clearly, when ignorePath is true, you want to ignore the if statement? So there's no need to OR, this is third AND condition.

if (ignorePath == false && tempPath != null && tempPath.Length != 0)
{

}


It looks like tempPath is a string, so you might write your code like:

if(!string.IsNullOrEmpty(tempPath) && !ignorePath)
{

}

You want the and && operator, since you want both conditions to be true to enter the if.


Change it like this :

if (!ignorePath)
   if ((tempPath != null) && (tempPath.Length != 0)))
{
}

or

if (!ignorePath && ((tempPath != null) && (tempPath.Length != 0)))
{
}
0

精彩评论

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

关注公众号