Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper and remove redundant parentheses. OR vs AND logic in C#

Tags:

c#

resharper

I recently noticed that ReSharper (2016.3) is now saying to remove redundant parentheses on C# statements that, I believe, would cause the intended behavior to change. Is this statement:

private bool GetAutoAdjust( int catType )
{
  return ( catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen ) ||
         ( catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt ) ||
         ( catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis );
}

Really equivalent to this one?

private bool GetAutoAdjust( int catType )
{
  return  catType == ChargeTypeIds.Penalty && _appSettingRepository.AutoRemovePen  ||
          catType == ChargeTypeIds.Interest && _appSettingRepository.AutoRemoveInt  ||
          catType == ChargeTypeIds.Discount && _appSettingRepository.AutoRemoveDis ;
}

Perhaps I am wrong in how C# evaluates OR clauses compared to something like SQL Server, but doesn't OR evaluate the expression just to the LEFT of it and just to the right of it or does it actually pre-concatenate all of the AND conditions prior to evaluating an OR condition?

like image 210
Rob Packwood Avatar asked Mar 22 '17 01:03

Rob Packwood


1 Answers

In C# there is an order of precedence for operators. From the docs you can see that && comes before || so technically Resharper is correct that those parentheses are redundant.

Having said that, it you feel it is more obvious to leave them in - then leave them in. Readability of code should always be a priority.

like image 66
DavidG Avatar answered Oct 26 '22 23:10

DavidG