handling nulls in c#-Collection of common programming errors
I have an object like this:
class MyObject
{
public string Object.Prop1 { get; set; }
public string Object.Prop2 { get; set; }
}
I’m writing a custom JSON converter and I’m serializing this object like this:
Dictionary OutputJson = new Dictionary();
OutputJson.Add("TheProp1", MyObject.Prop1.Trim());
If for some reason Prop1
is null
, will the code encode TheProp1
as ""
or will it crash?
-
If
Prop1
isnull
your code will throw aNullReferenceException
. You need to test ifProp1
is null before callingTrim
:MyObject.Prop1 == null ? "" : MyObject.Prop1.Trim()
Or you can do it more concisely with the null-coalescing operator:
(MyObject.Prop1 ?? "").Trim()
-
It will crash with a
NullReferenceException
, since you can’t callTrim
onnull
. You could do this instead:OutputJson.Add("TheProp1", MyObject.Prop1 == null ? string.Empty : MyObject.Prop1.Trim());
-
My understanding is that a null is not an empty string. If you want to insure that this is going to work simply wrap the Value of the add in an if and insert your empty string as the null place holder. Of course you’ll need to take the appropriate action when you decode your json.
-
Another way to handle this is to use private member to handle the property values of properties where you need a default value rather than null
Class MyObject { private string _prop1 = String.Empty; public string Object.Prop1 { get { return _prop1; } set { _prop1 = value; } } }
-
If you don’t need polymorphic behaviour for MyObject you can declare it as a struct instead of a class. It will have value semantic and every value will be initialize using its default. I am assuming inside your class you have just struct type (eg. int, string, double).