Home > Mobile >  c# Is there a cleaner way setting the same flag boolean variable to true within multiple if statemen
c# Is there a cleaner way setting the same flag boolean variable to true within multiple if statemen

Time:03-03

I have an example like this and I was wondering if there was a cleaner way to assign true to the same variable. The if statements are only for example purposes. The question is not about the if statements but just trying to find a cleaner way to do this rather than submitting the same flag to true over and over.

public static bool CheckForCondition(DateTime a, DateTime b, bool conditionFlag)
{
     if (a > b)
     {
          conditionFlag = true;
     }
     else if (b < a)
     {
          conditionFlag = true;
     }
     else if (a == b)
     {
          conditionFlag = true;
     }

     return conditionFlag;
}

My goal was to avoid the repetition of the same code and make it cleaner if possible.

CodePudding user response:

This will be fine:

public static bool CheckForCondition(DateTime a, DateTime b, bool conditionFlag) 
  => conditionFlag || a >= b;

You accept a bool and overwrite it to true if a is >= b. Because you never set it to false it means it's effectively an OR operation.. The only way you get a false out is if it's a false in and b > a.

CodePudding user response:

The first 2 if statements are basically the same thing you do not need to check both, you could also use greater than or equal to condition to combine the first and third if statements.

conditionFlag = false    
if (a >= b)
{
    conditionFlag = true;
}

return conditionFlag;

Edit: This assumes that you want the function to return false if none of the conditions are true, otherwise Caius Jard's answer is better. Can also be simplified even more as mentioned by Matthew Watson in the comments.

  •  Tags:  
  • c#
  • Related