Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling nulls in c#

Tags:

c#

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?

like image 548
frenchie Avatar asked Dec 17 '22 06:12

frenchie


2 Answers

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()
like image 129
Mark Byers Avatar answered Jan 01 '23 11:01

Mark Byers


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;
            } 
      }

}
like image 28
Maess Avatar answered Jan 01 '23 13:01

Maess