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?

  1. 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()
    
  2. It will crash with a NullReferenceException, since you can’t call Trim on null. You could do this instead:

    OutputJson.Add("TheProp1", MyObject.Prop1 == null ?
                                   string.Empty :
                                   MyObject.Prop1.Trim());
    
  3. 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.

  4. 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;
                } 
          }
    
    }
    
  5. 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).