Is this code actually redundant?

Answered

We had introduced code like this:

if (response != null && response.Success && response.Result is bool == true)

Resharper marks the ' == true' as redundant but is this actually true?

I would have expected that 'is bool' expression would only verify the type and would not evaluate the value.

Or perhaps C# shortcuts this for 'bool'?

 

0
3 comments

Simon Kennedy, thank you for your question.

"is bool == true" expression only checks the type. Even if we assume that the value of "response.Result" will be false, the following condition will be met:

response.Result = false;
if (response.Result is bool == true)
{
// block of code to be executed
}

This is not Rider specific, Visual Studio behaves the same. Please let me know if you have any other questions.

0

Oops, the example was supposed to be:

if (response != null && response.Success && response.Result is bool boolValue == true)

where 'boolValue == true' is marked as redundant. The following however is fine.

if (response != null && response.Success && response.Result is bool boolResult && boolResult)

I guess the take from this is that you have to logical && to evaluate the actual variable and it cannot be done in the same expression.

0

Simon Kennedy, these examples also can be checked during debugging. As described earlier, the following condition "response.Result is bool boolValue == true" will be met even if the "response.Result" is false. This means that the right side "== true" is not used. If "boolValue" value is also highlighted as redundant, then most likely it is not used anywhere and can be safely removed.

In the second example "response.Result is bool boolResult && boolResult" boolResult is used, so it's cannot be removed from the part to the left of the "&&".

I also tested these two cases in VS: the behavior is the same there. Please let me know if I am missing something.

 

0

Please sign in to leave a comment.