Search code examples
c#coding-style

Using if (!bool) vs if (bool == false) in C#


Is there any sort of style consensus on the following two coding styles? I'm more curious if this is the sort of thing where one is generally preferred in good code in C#, or if this the sort of thing that gets decided when picking a style for a coding project.

Style 1: Using the ! sign to indicate a not in a conditional

if (!myBool)
{
  //Do Stuff...
}

Style 2: Using == false to indicate a check for falsehood in a conditional

if (myBool == false)
{
  //Do Stuff...
} 

Thanks!


Solution

  • The normal convention is

    if (!myBool)
    

    The one place where I don't go this route is with nullable booleans. In that case I will do

    if (myBool == true)
    {
    
    }
    

    Which is equivalent to

    if (myBool.HasValue && myBool.Value)