Reputation: 51947
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?
Thanks.
Upvotes: 36
Views: 113354
Reputation: 26632
You can use elvis operator, also known as "null-conditional-operators":
GetNullableString()?.Trim(); // returns NULL or trimmed string
Upvotes: 44
Reputation: 11
Recently I had to check a string if it is null, empty or whitespace using just one if condition and for that I found out that you can add "" to a null string to make it non null.
string test = GetStringFromSomeWhere(); // null
if(string.IsNullOrEmpty(test.Trim())) { return true; } // Exception
So I did this instead
string test = GetStringFromSomeWhere() + ""; // ""
if(string.IsNullOrEmpty(test.Trim())) { return true; } // true
Upvotes: 1
Reputation: 224963
No, it would not be better to initialize TheText
to ""
. You're assigning to it right afterwards.
No, it won't crash – Trim()
works just fine on an empty string. If by "empty" you mean that it can be null, then yes, it will crash; you could have null remain null with a null-conditional call:
string TheText =
serializer.ConvertToType<string>(dictionary["TheText"])?.Trim();
Upvotes: 6
Reputation: 20862
Some basic techniques to check strings against null
before you trim:
(mystring ?? "").Trim()
??
will return the first operand. Only when this operand is null, the second operand will be returned (as a kind of default value).mystring?.Trim()
?
will short cirtuit a chain of operations in dot-notation. If the operand is null, the following operations will not be executed and null will be returned.if( string.IsNullOrWhiteSpace(mystring) ) { ... }
IsNullOrWhiteSpace()
method may replace trimming if you actually want to check if there is real content in mystring. It returns true if the operand is null, empty, or nothing but whitespace characters.Upvotes: 18
Reputation: 1
You can use this code as beblow
string theText = (((serializer.ConvertToType<string>(dictionary["TheText"])))+ string.Empty).Trim();
Upvotes: 0
Reputation: 13115
As suggested in some of the comments, you may now use c# 6 Null-conditional operators with this syntax:
string TheText = (serializer.ConvertToType<string>(dictionary["TheText"]))?.Trim();
Documentation: https://msdn.microsoft.com/en-us/library/dn986595.aspx
Upvotes: 6
Reputation: 10374
If you have a few fields you wish to trim but your getting exceptions for those records that have nulls in certain fields, then writing a quick extension method will be the easiest method:
public static class ExtensionMethods
{
public static string TrimIfNotNull(this string value)
{
if (value != null)
{
return value.Trim();
}
return null;
}
}
Sample example of use:
string concatenated = String.Format("{0} {1} {2}", myObject.fieldOne.TrimIfNotNull(), myObject.fieldTwo.TrimIfNotNull(), myObject.fieldThree.TrimIfNotNull());
Upvotes: 16
Reputation: 133024
Calling Trim()
on an empty string will result in an empty string. Calling Trim()
on null
will throw NullReferenceException
Upvotes: 18
Reputation: 499072
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();
}
Upvotes: 27