3

I am trying to add items to a list using for the following;

public class Reason
{
    [JsonProperty("code")]
    public int Code { get; internal set; }
}

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

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

    [JsonProperty("reason")]
    public Reason reason { get; set; } = new Reason();
}

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

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

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

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

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


root.items.Add(new Item { Id = 8675072, quantity = 1, Reason.Code = 2  });

I am getting the following error when i am trying to add the Reason.Code,

An Object Reference is required for the non-field, method or property.

Where would i need to initialise to add Reason.Code to the list?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Mayamiko
  • 105
  • 1
  • 1
  • 8

1 Answers1

0
root.items.Add(new Item { Id = 8675072, quantity = 1, reason = { Code = 2  }})
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • How is this `= { SomeProperty = value }` part is called? It looks like property initializer, but I was sure it can only be used with `new`. – Sinatr Mar 11 '20 at 11:36
  • @Sinatr See https://stackoverflow.com/questions/16794925/nested-object-initializer-syntax – Matthew Watson Mar 11 '20 at 11:44