Check if a string is null or empty, otherwise trim it

You could go a step futher of what Justin Harvey suggested and implement an extension method (in a static class, of course) like this:

public static string TrimmedOrDefault(this string str, string def)
{
    if (string.IsNullOrEmpty(str)) //or if (string.IsNullOrWhiteSpace(str))
    {
        // Hmm... what if def is null or empty?
        // Well, I guess that's what the caller wants.
        return def; 
    }
    else
    {
        return str.Trim();
    }
}

Then you can use it like this:

dummy.Title = ds1Question.Title.TrimmedOrDefault("Dummy title");

Perhaps:

dummy.Title = string.IsNullOrEmpty(ds1Question.Title)
             ? "Dummy title" : ds1Question.Title.Trim();

or

dummy.Title = string.IsNullOrWhiteSpace(ds1Question.Title)
             ? "Dummy title" : ds1Question.Title.Trim();

This is invalid:

 ds1Question.Title.null

You can have:

dummy.Title = ds1Question.Title == null ? "Dummy title"
                                        : ds1Question.Title.Trim();

Or use:

dummy.Title = (ds1Question.Title ?? "Dummy title").Trim();

That will perform unnecessary trimming to the default value, but it's simple.

These will only check for nullity though. To check for empty as well, you need to call String.IsNullOrEmpty, which I'd do via an extra variable for sanity:

string title = ds1Question.Title;
dummy.Title = string.IsNullOrEmpty(title) ? "Dummy title" : title.Trim();

Alternatively use IsNullOrWhitespace as per Marc's answer, to avoid having a title of " " which isn't empty until it's trimmed.

Tags:

C#

String

Null