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<string, object> OutputJson = new Dictionary<string, object>();
OutputJson.Add("TheProp1", MyObject.Prop1.Trim());
If for some reason Prop1 is null, will the code encode TheProp1 as "" or will it crash?
If
Prop1isnullyour code will throw aNullReferenceException. You need to test ifProp1is null before callingTrim:Or you can do it more concisely with the null-coalescing operator: