.Trim() when string is empty or null

If the serializer returns an empty string, Trim will do nothing.

If the serializer returns null, you will get a NullReferenceException on the call to Trim.

Your code would be better written (as far as initialization is concerned) like this:

string theText = 
            ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());

There is no point in declaring and initializing the variable and the immediately assigning to it.

The following would be safest, if you don't know what the serializer might return:

string theText = ((serializer.ConvertToType<string>(dictionary["TheText"])));

if(!string.IsNullOrEmpty(theText))
{
    theText = theText.Trim();
}

You can use elvis operator:

GetNullableString()?.Trim(); // returns NULL or trimmed string

Tags:

C#