user726720
user726720

Reputation: 1237

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.

Upvotes: 4

Views: 7541

Answers (3)

Steve
Steve

Reputation: 216293

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));

Upvotes: 13

Lockdowne
Lockdowne

Reputation: 484

You can do: sb.Append(key?.PadRight(33));

Upvotes: 1

atomSmasher
atomSmasher

Reputation: 1465

I am not sure if this is what you are looking for?

if (key != null)
    sb.Append(key.PadRight(33));
else
    sb.Append("".PadRight(33));

Upvotes: 1

Related Questions