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:
private string _Name = string.Empty;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value ?? string.Empty;
}
}
However, what you're looking for is probably the ??
operator, also known as the null-coalescing operator, as used above, basically, this expression:
x = y ?? z;
means the same as this:
if (y != null)
x = y;
else
x = z;
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:
var temp = y;
if (temp != null)
x = temp;
else
x = z;