Zero handling in C #

I have an object like this:

class MyObject { public string Object.Prop1 { get; set; } public string Object.Prop2 { get; set; } } 

I am writing a custom JSON converter, and I serialize this object as follows:

 Dictionary<string, object> OutputJson = new Dictionary<string, object>(); OutputJson.Add("TheProp1", MyObject.Prop1.Trim()); 

If for some reason Prop1 is null , will Prop1 be encoded as "" or will it crash?

+4
source share
6 answers

If Prop1 is null , your code will throw a NullReferenceException . You need to check if Prop1 is null before calling Trim :

 MyObject.Prop1 == null ? "" : MyObject.Prop1.Trim() 

Or you can do it more briefly with the null-coalescing statement :

 (MyObject.Prop1 ?? "").Trim() 
+9
source

It will work with a NullReferenceException , since you cannot call Trim on null . You could do this instead:

 OutputJson.Add("TheProp1", MyObject.Prop1 == null ? string.Empty : MyObject.Prop1.Trim()); 
0
source

I understand that zero is not an empty string. If you want to make sure this will work, just wrap the add value in if and insert an empty string as the owner of the zero place. Of course, you need to take appropriate action when you decrypt your json.

0
source

Another way to handle this is to use a private member to handle property property values, where you need the default value, not null

 Class MyObject { private string _prop1 = String.Empty; public string Object.Prop1 { get { return _prop1; } set { _prop1 = value; } } } 
0
source

If you do not need polymorphic behavior for MyObject, you can declare it as a struct instead of a class. It will have a semantic value and each value will be initialized using its default value. I assume that inside your class you only have a structure type (e.g. int, string, double).

0
source

you can use the DBNull class when populating an object

 UserName = DBNull.Value != reader["UserName"] ? reader["UserName"].ToString() : default(string); 
0
source

Source: https://habr.com/ru/post/1385417/


All Articles