C# Tips n Tricks: ToStringOrEmpty()

Here is another one of those extension methods that I carry with me from job to job.  It’s a super simple one that just makes sense.  So many times I am working with variables that need to be displayed as empty strings when they are null.  The following code gets tiresome when generating dozens of strings in a row.

var displayString = value == null ? String.Empty : value.ToString();

Instead I added the following extension method for strings. Technically it works for any object that has ToString() implemented.

It means that I can simply show the following code which is much simpler and nicer and cleans my code up tremendously.

        public static string ToStringOrEmpty(this object value)
            return ((object)value ?? String.Empty).ToString();

Update: A former co-worker sent me this CodeProject Article: Chained null checks and the Maybe monad that takes this concept a bit further with a fairly complex set of extensions that allow cleaning up null checks even more.  I’ll have to dig into it deeper.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s