Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Null to `StringBuilder`

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.

like image 847
user726720 Avatar asked Oct 23 '25 09:10

user726720


1 Answers

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));
like image 87
Steve Avatar answered Oct 25 '25 22:10

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!