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