6

I have these 2 classes:

    class Customer
    {
        public string Name;
        public string City;
        public Order[] Orders;
    }
    class Order
    {
        public int Quantity;
        public Product Product;
    }

And then in the Main I do the following:

            Customer cust = new Customer
            {
                Name = "some name",
                City = "some city",
                Orders = {
                    new Order { Quantity = 3, Product = productObj1 },
                    new Order { Quantity = 4, Product = productObj2 },
                    new Order { Quantity = 1, Product = producctObj3 }
                }
            };

But I cannot initialize the array ... with a collection initializer. And I know that this, i.e., is possible string[] array = { "A" , "B" }; which looks the same to me...

Of course I could make separate objects of Order, put them in an array and then assign it toOrders , but I don't like the idea.

How can I achieve the clean and less-code-solution in this case?

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96

2 Answers2

11

C# does not provide JSON style notation for object initialization, because it is strongly statically typed language, that does not use aggressive type inference. You have to call array constructor(new Order[]) before using initializer code:

        Customer custKim = new Customer
        {
            Name = "some name",
            City = "some city",
            Orders = new Order[]{
                new Order { Quantity = 3, Product = productObj1 },
                new Order { Quantity = 4, Product = productObj2 },
                new Order { Quantity = 1, Product = producctObj3 }
            }
        };
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
8

Jeroen and Eugene have provided some good options, but the truth is that you CAN use the syntax that you provided in your description if you use generic Lists, Collections and other types, but not with simple arrays.

So if you define your Customer class as:

class Customer
{
    public Customer()
    {
        Orders = new List<Order>();
    }

    public string Name;
    public string City;
    public List<Order> Orders;
}

You can use the syntax that you wanted to use in the first place:

Customer cust = new Customer
{
    Name = "some name",
    City = "some city",
    Orders = {
        new Order { Quantity = 3, Product = productObj1 },
        new Order { Quantity = 4, Product = productObj2 },
        new Order { Quantity = 1, Product = producctObj3 }
    }
};
Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
  • Did the C# standard change at some point? Currently `Orders = { ... }` is an **array** initializer. Works if `public Order[] Orders;`. Given `public List Orders;`, result is compiler complaint "array initializer can only be assigned to an array type." – ToolmakerSteve Mar 13 '21 at 04:23