lundi 9 mars 2020

C# initialise List property [duplicate]

I have the following class which contains a list

        public class Item
       {
        [JsonProperty("variantId")]
        public int variantId { get; set; }

        [JsonProperty("quantity")]
        public int quantity { get; set; }

        [JsonProperty("returnReason")]
        public int returnReason { get; set; }
    }

    public class RootObject
    {
        [JsonProperty("dropOff")]
        public DropOff dropOff { get; set; }

        [JsonProperty("providerId")]
        public int providerId { get; set; }

        [JsonProperty("Reference ")]
        public string Reference { get; set; }

        [JsonProperty("returnMethodId")]
        public int returnMethodId { get; set; }

        [JsonProperty("items")]
        public List<Item> items { get; set; }

I want to add items to the list, which i am doing here in a different class;

        Booking.RootObject root = new Booking.RootObject();
        root.providerId = 111;
        root.Reference = "ytrhtew";
        root.returnMethodId = 1;
        root.items.Add(new Item { variantId = 1, quantity = 1, returnReason = 2 });

It is failing for the following reason - Object reference not set to an instance of an object

How would i need to initialise this for it to work so that i can add items to the list?

Aucun commentaire:

Enregistrer un commentaire