Search code examples
c#object.net-coregeneric-collections

How to add value to list when using object initializer?


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; }
}

Solution

  • 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: