C# initialize object

The first 3 lines of code works fine..

How can I do the same when using object initializer ?

// works
Customer MyCustomerx = new Customer();
MyCustomerx.Location[0].place = "New York";
MyCustomerx.Location[1].place = "France";

// problem here
List<Customer> MyCustomer = new List<Customer>
{
 new Customer() { Name= "Me",Location[0].place = "New York" }
}
Jon Skeet
people
quotationmark

There's no equivalent of that code within object initializers - you can't specify indexers like that. It's slightly unusual that it works even directly... I'd expect to have to add to a Locations property, rather than there being two already available which I could set an unconventionally-named property on. For example, this would be idiomatic:

Customer customer = new Customer {
    Name = "Me",
    Locations = {
        new Location("New York"),
        new Location("France")
    }
};

(I'd probably put the name into a constructor parameter, mind you.)

You could then use that within a collection initializer, of course.

people

See more on this question at Stackoverflow