2
private PostDto MapIntegration(IntDto integ)
{
    return new PostDto
    {
        prop1 = "7",
        prop2 = "10",
        prop3 = true,
        prop4 = "EA Test",
        product_list.Add(integ) // ERROR This says the name product_list does not exist in current context
    };
}

And when we look at PostDto

public class PostDto 
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public bool prop3 { get; set; }
    public string prop4 { get; set; }
    public List<IntDto> product_list { get; set; }
}
Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102

2 Answers2

5

Collection Initializers only allow you to assign values to the object's properties or fields. You can't access a member of a property of the object inside the object initializer as you normally would in other places of the code. Plus, even if you had that option, the list isn't even initialized so you can't call the .Add() method.

Instead, you may initialize the list using a collection initializer so that you can directly add the IntDto item to it in one go:

private PostDto MapIntegration(IntDto integ)
{
    return new PostDto
    {
        prop1 = "7",
        prop2 = "10",
        prop3 = true,
        prop4 = "EA Test",
        // Create a new list with collection initializer.
        product_list = new List<IntDto>() { integ }
    };
}

References:

  • it works, thanks! Could you little bit explain how come you added new item to list on a way like you did { newItem }. :) – Roxy'Pro Oct 23 '19 at 10:42
  • @Roxy'Pro That's called collection initializer, which allows you to add one or more elements when initializing a collection. Check the link I added under "References" for more information. – 41686d6564 stands w. Palestine Oct 23 '19 at 14:24
1

product_list isn't initialized.

private PostDto MapIntegration(IntDto integ)
{
    var ret = new List<IntDto>();
    ret.Add(integ);
    return new PostDto
    {
        prop1 = "7",
        prop2 = "10",
        prop3 = true,
        prop4 = "EA Test",
        product_list = ret
    };
}

Construct a temporary list or something else that can be used.

nulltron
  • 637
  • 1
  • 9
  • 25