I have an object with string
properties, for example, a Patient object with weight and height.
But when the property is null, my code fails when I try to use it, as the property is set to null. I'm trying to create a function that checks if the string/property is null, and if so, set the property to ""
.
I know that I can do this:
if(string.isNullOrEmpty(patient.weight)) patient.weight = "";
But I need the code to be as clean as possible, and I have a lot of properties, so I don't want to manually check each one. Ideally, I'd like to have a function that can take the string, (without failing even if it is null), and simply return either the value if it's not null, or a ""
if it is null.
Can anyone give me a clue on this?
Personally I would ensure those properties can never be null by writing them like this:
However, what you're looking for is probably the
??
operator, also known as the null-coalescing operator, as used above, basically, this expression:means the same as this:
and that's not entirely true either. In the above example
y
is evaluated twice, which does not happen with the??
operator so a better approximation would be this: