Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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; }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading