I'm reading from an XML file and building string using StringBuilder. But sometimes my Element.Attributes are missing in which case the string is null.
string key = (string)EventId.Descendants("properties").Elements("ID").Attributes("key").FirstorDefault();
After getting all the attribue values I'm doing a string build:
sb.Append(key.PadRight(33));
But sometimes the value of key can be null, in which it gives an error:
Check to determine if the object is null before calling the method
I want to append empty string to StringBuilder even if the value is null.
You can simply write
sb.Append((key ?? "").PadRight(33));
The ?? is called the Null-Coalescing operator
Its job consist in evaluating the left side value and, if this value is null, then return the right side value. Or in other words it is a shortcut for
sb.Append((key == null ? "" : key).PadRight(33));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With