Home > Mobile >  Return null when passing data exists in c#
Return null when passing data exists in c#

Time:10-19

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?

enter image description here

Looking forward to anyone's help or suggestions. Thank you

CodePudding user response:

You are not creating an instance of the LocationModelBase on either the origin or destination so they default to null.

Either create them before you assign...

addGetdata.origin = new LocationModelBase();
addGetdata.origin.code = "ABC";
addGetdata.destination = new LocationModelBase();
addGetdata.destination.code = "DYF";

Or alternatively, create them as part of the construction of the class...

public LocationModelBase origin { get; set; } = new LocationModelBase();
public LocationModelBase destination { get; set; } = new LocationModelBase();

CodePudding user response:

When initializing your DataModel class, you need to need initialize the other classes used for your model.

public LocationModelBase origin { get; set; }
public LocationModelBase destination { get; set; }

These properties have a type of another class and must be initialized before assigning values to that class' properties.

var addGetdata = new DataModel
{
    origin = new LocationModelBase
    {
        code = "ABC"
    }
    destination new LocationModelBase
    {
        code = "DYF"
    }
    ...
}
  • Related