2

So I have this code that POST a JSON data to my REST API using c#

try
    {
        tempquantityofmenu = entQuantity.Text;
        CustList custo = new CustList();

        CustomerOrder custo1 = new CustomerOrder()
           {
              menu_name = tempnameofmenu,
              menu_quantity = tempquantityofmenu,
              menu_code = tempcodeofmenu
            };

        custo.CUSTOMER_ORDER.Add(custo1);

        await Navigation.PushAsync(new OrdernowCategory());
       }
        catch(Exception ex)
        {
            DisplayAlert("error", ex.ToString(), "OK");
        }

Then I am getting this System.NullReferenceExeption: Object Reference not set to an instance of an object

public class CustomerOrder
{
    public string menu_name { get; set; }
    public string menu_quantity { get; set; }
    public string menu_code { get; set; }
}

public class CustList
{
    public List<CustomerOrder> CUSTOMER_ORDER { get; set; }
}

I think my problem here is that when adding a item to the CUSTOMER_ORDER inside the try catch is not working

Abdul Kawee
  • 2,598
  • 1
  • 12
  • 26
ropenrom24
  • 368
  • 3
  • 12

2 Answers2

3

You can either

public class CustList
{
    public List<CustomerOrder> CUSTOMER_ORDER { get; set; } = new List<CustomerOrder>();
}

or

public class CustList
{
    public List<CustomerOrder> CUSTOMER_ORDER { get; set; } 

    public CustList()
    {
        CUSTOMER_ORDER = new List<CustomerOrder>();
    }
}

or

custo.CUSTOMER_ORDER = new List<CustomerOrder>();
custo.CUSTOMER_ORDER.Add(custo1);

And for the love of all things neat and tidy in this world, don't name your variables/properties/or andything with capitals and underscores

TheGeneral
  • 69,477
  • 8
  • 65
  • 107
3

Because you didn't create an instance for CUSTOMER_ORDER property, CUSTOMER_ORDER is reference types, which have null values by default.

If you want to solve it you can give CUSTOMER_ORDER an instance collection like this.

CustList custo = new CustList() { 
     CUSTOMER_ORDER = new List<CustomerOrder>() 
};
D-Shih
  • 31,624
  • 6
  • 20
  • 39