frenchie frenchie - 1 year ago 142
C# Question

.Trim() when string is empty or null

I'm receiving some data from the client in the form of json.
I'm writing this:

string TheText; // or whould it be better string TheText = ""; ?
TheText = ((serializer.ConvertToType<string>(dictionary["TheText"])).Trim());

If the variable that's being parsed from json comes back empty, does this code crash when I call the .Trim() method?


Answer Source

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 = 

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

    theText = theText.Trim();