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 Prop1
is null
your code will throw a NullReferenceException
. You need to test if Prop1
is null before calling Trim
:
MyObject.Prop1 == null ? "" : MyObject.Prop1.Trim()
Or you can do it more concisely with the null-coalescing operator:
(MyObject.Prop1 ?? "").Trim()
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With