I have a problem that I am confused. I have a piece of code that executes a Post API command like this:
{
"chargeCriterias": null,
"containerType": "Dry",
"origin": {
"code": "ABC"
},
"destination": {
"code": "DYF"
},
"dateBegin": "2022-10-01T00:00:00",
"dateEnd": "2022-11-30T23:59:59",
"ratesFetcher": "XYZ",
}
I’m trying to write code to execute a command like this:
public class DataModel
{
public LocationModelBase origin { get; set; }
public LocationModelBase destination { get; set; }
public string dateBegin { get; set; }
public string dateEnd { get; set; }
public string chargeCriterias { get; set; }
public string containerType { get; set; }
public string ratesFetcher { get; set; }
}
public class LocationModelBase
{
public Int32 locationId { get; set; }
public string code { get; set; }
}
var addGetdata = new DataModel();
{
addGetdata.origin.code = "ABC";
addGetdata.destination.code = "DYF";
addGetdata.dateBegin = "2022-10-01T00:00:00";
addGetdata.dateEnd = "2022-11-30T23:59:59";
addGetdata.chargeCriterias = null;
addGetdata.containerType = "Dry";
addGetdata.ratesFetcher = "SSSS";
}
However I get the error: 'Object reference not set to an instance of an object.'
.
I have checked the place value: addGetdata.origin and it says null. However I tried the ways but still didn’t solve the problem. Where did I go wrong?
Looking forward to anyone’s help or suggestions. Thank you
2
Answers
You are not creating an instance of the
LocationModelBase
on either theorigin
ordestination
so they default tonull
.Either create them before you assign…
Or alternatively, create them as part of the construction of the class…
When initializing your
DataModel
class, you need to need initialize the other classes used for your model.These properties have a type of another class and must be initialized before assigning values to that class’ properties.