LearningAsIGo
LearningAsIGo

Reputation: 1311

C# - Create object without null properties

I am new to C# and having difficulty with creating an object of a class using serialized json string. I have class defined with some member variable as follows:

class someClass{
   someclass(serializedJson) {
      JavascriptSerializer js = new JavascriptSerializer();
      var newObj = (someClass)(js.deserialize(serializedJson, typeof(serializedJson)));

   }
   // class has bunch of private and public member variables eg
   private string this._value;
   public string Price{
     get {
       return _price;
     }
     set {
       _price = somePrice;
     }
   }

}

Class is being called in some other file to create an object as:

var obj = new someClass(serializedJsonString);

serializedJsonString looks like:

{
  ... : ...,
  ... : ...
  // contains no key value pair for Price that I am trying to reference in constructor above. In other words, constructor should treat it as null.
}

Obviously, my obj is getting created with obj.Price being null.

Is there a way to:

1) Modifying getter/setter for Price to not have it has property for obj if its not coming in from serializedJson?

2) Remove the property "Price" from object because its null?

Upvotes: 1

Views: 1577

Answers (2)

GDI89
GDI89

Reputation: 54

If you have value for Price field in deserialize object, then you must create public string Price { get; set; } and add suitable attribute, else if Price is depend on deserialized object then:

someclass(serializedJson)
{
    JavascriptSerializer js = new JavascriptSerializer();
    var newObj = (someClass)(js.deserialize(serializedJson, typeof(serializedJson)));
    Price = // ... some code
}
pblic string Price { get; }

Upvotes: 0

Ignasi93
Ignasi93

Reputation: 693

You can't remove a property of an object dynamically, but you can use the getter to give the null value and return whatever you need, for example:

get
{
    return _price ?? string.Empty;
}

Upvotes: 1

Related Questions