Search code examples
c#nullnullablenull-check

Writing a more refined and simplified null check c#


I have the following code,

bool HasPassed= (result!= null && result.Identifier.Equals("Passed"))? true : false

This works fine as it is, but I was wondering if it were possible to write this code in a better and more simplified way, maybe using the ? operator ( or Null-coalescing operator). I'm still learning about this and did not quite understand how it can be used in this case. Below is a minimal project to test it out and any advice is much appreciated!

Result result = new Result();
//result.Identifier = "Passed";
result = null;
bool HasPassed = (result != null && result.Identifier.Equals("Passed")) ? true : false;

public class Result
{
    public string Identifier { get; set; }
}

Solution

  • Firstly, any time you have a conditional of the form condition ? true : false, you can just replace it with condition.

    So you can start with:

    bool HasPassed= (result!= null && result.Identifier.Equals("Passed"));
    

    You can then remove the parentheses and rename the local variable to follow .NET naming conventions:

    bool hasPassed = result != null && result.Identifier.Equals("Passed");
    

    Finally, use the null-conditional operator and the == overload for string:

    bool hasPassed = result?.Identifier == "Passed";
    

    Just as safe, but much more readable and concise IMO.