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

C# Null check handling failing

I am struggling to handle a null check in-line, can someone help identify where I am going wrong please?

When passing in a null intentionally, I want to handle it and want x to be an empty string. If it isn’t Null, I want it to be the value set.

var x = string.IsNullOrEmpty(ViewModel.OccupationRefer.ToString()) ? string.Empty : ViewModel.OccupationRefer.ToString();

The above with a null passed into ViewModel.OccupationRefer, throws a null exception.

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 :

var x = ViewModel?.OccupationRefer?.ToString() ?? "";

This uses null-conditional (?.) and null-coalescing (??) operations so that if either ViewModel or ViewModel.OccupationRefer are null, or if the ToString() returns null: you get ""

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