Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Nested Object Initializer Syntax and Behavior

Learn how C# nested object initializers work, including the assignment and nested-member forms, collection initialization, common mistakes, and tradeoffs.

~5 min readC#
#C##Object Initializer#Nested Objects#Collection Initializer
Diagram showing nested object initializer syntax in C# with braces and property assignments.

A C# nested object initializer is an object initializer embedded in another object initializer. It lets you construct and populate a property object in the same expression that constructs its parent. This pattern is common when building DTOs, configuration models, or test fixtures. The syntax is concise, but the two main forms have different setter and getter requirements, so it helps to know how the compiler processes them.

What a Nested Object Initializer Looks Like

The core syntax extends a standard object initializer by placing another object initializer after a property assignment. Suppose you have two classes:

csharp
public class Address { public string Street { get; set; } public string City { get; set; } } public class Customer { public string Name { get; set; } public Address HomeAddress { get; set; } }

You can initialize a Customer and its HomeAddress in one statement:

csharp
var customer = new Customer { Name = "Alice", HomeAddress = new Address { Street = "123 Main St", City = "Springfield" } };

The inner new Address { ... } is a standard object initializer. The outer initializer assigns that new object to the HomeAddress property.

There are two forms to keep in mind:

  • HomeAddress = new Address { ... } assigns a new object to HomeAddress. It requires an accessible setter on HomeAddress.
  • HomeAddress = { ... } modifies the existing object returned by HomeAddress. It requires an accessible getter and an existing, non-null object, and it does not call the setter on HomeAddress.

The Address properties still require accessible setters when a new Address is created with new Address { ... }.

How Nested Initializers Behave at Runtime

Object initializers are syntactic sugar. The compiler translates the earlier HomeAddress = new Address { ... } example into code roughly equivalent to:

csharp
var customer = new Customer(); customer.Name = "Alice"; customer.HomeAddress = new Address(); customer.HomeAddress.Street = "123 Main St"; customer.HomeAddress.City = "Springfield";

This means the constructor of the outer object runs first, then each property assignment is processed in the order written. For the assignment form, the inner object is constructed and its properties are set before the outer setter receives it. The outer object's constructor cannot see the initializer values while it runs, because those assignments happen after construction. If the outer constructor throws, the inner object is never created.

For the nested-member form, the compiler evaluates the getter for HomeAddress and sets members on the returned object. It does not call the HomeAddress setter. That is why a read-only collection property initialized to an empty collection can still be populated from an object initializer.

Initializing Collections Inside Objects

Nested object initializers combine naturally with collection initializers. For example, a class that holds a list of addresses:

csharp
public class Customer { public string Name { get; set; } public List<Address> Addresses { get; } = new List<Address>(); }

You can populate the list directly in the initializer:

csharp
var customer = new Customer { Name = "Bob", Addresses = { new Address { Street = "1 Oak Ave", City = "Portland" }, new Address { Street = "2 Pine Rd", City = "Eugene" } } };

Here the Addresses property is read-only, but the collection initializer works because it calls Add on the existing list. The compiler treats the collection member as calls to Add on the existing list, roughly equivalent to:

csharp
var customer = new Customer(); customer.Name = "Bob"; customer.Addresses.Add(new Address { Street = "1 Oak Ave", City = "Portland" }); customer.Addresses.Add(new Address { Street = "2 Pine Rd", City = "Eugene" });

This pattern is useful when the collection is initialized in the constructor or as a property initializer, ensuring it is never null.

Mixing Object and Collection Initializers

You can nest collection initializers inside object initializers and vice versa. Consider a class representing an order with line items:

csharp
public class Order { public int Id { get; set; } public List<OrderLine> Lines { get; } = new List<OrderLine>(); } public class OrderLine { public string Product { get; set; } public int Quantity { get; set; } }

A single expression can create the order, its lines, and each line's properties:

csharp
var order = new Order { Id = 42, Lines = { new OrderLine { Product = "Laptop", Quantity = 1 }, new OrderLine { Product = "Mouse", Quantity = 2 } } };

This is convenient for test data or small fixed configurations. The readability is high because the entire object graph is visible at once. However, if the collection is large or built dynamically, a separate method or loop may be clearer.

Common Mistakes and Their Fixes

A frequent error is using the nested-member form on a property that is null. If HomeAddress is not initialized in the constructor and has no default value, the following fails at runtime:

csharp
var customer = new Customer { Name = "Carol", HomeAddress = { Street = "5 Elm St" } // NullReferenceException at runtime };

There is no Address instance whose members can be set. The fix is to create one explicitly:

csharp
var customer = new Customer { Name = "Carol", HomeAddress = new Address { Street = "5 Elm St" } };

Setter requirements depend on which form you use. The assignment form HomeAddress = new Address { ... } needs an accessible setter on HomeAddress. The nested-member form HomeAddress = { ... } does not call the setter; it reads the current value of HomeAddress and modifies that object. That means the nested-member form can populate a read-only or private-setter property only if the property has an accessible getter and has already been initialized to an object. If you need to assign a brand-new object to a read-only property, do it in the constructor, field initializer, or factory method.

Also, be careful with reference cycles. If two objects reference each other, a nested initializer cannot create the cycle because one object must exist before the other. You would need to assign the second reference after both objects are constructed.

Readability and Maintainability Tradeoffs

Nested object initializers reduce boilerplate and keep related data together. For small, fixed object graphs, they improve readability. But for deep hierarchies, the indentation can become unwieldy. The order of assignments is fixed; it matters when setters have side effects, but for ordinary data objects it usually does not affect the final state. When the graph is built from dynamic input, a nested initializer is not suitable because you need conditional logic or loops.

A practical guideline is to use nested initializers when the structure is known at compile time and the number of nested elements is small. For larger or more variable structures, prefer building the object step by step or using a dedicated builder method. This keeps the code easier to debug because you can inspect intermediate states.

Performance and Allocation Considerations

Compared with writing the constructor calls and property assignments manually, a nested object initializer does not add extra runtime work; the object creation and property assignments are what allocate and modify objects. The only cost is the allocation of each object, which is inherent to the design. However, deeply nested initializers can create large object graphs in a single expression, making it harder to inspect memory usage if you are not careful. For example, if a collection initializer adds thousands of items, the Add method is called repeatedly, which may be less efficient than using a constructor that accepts a range. But for typical use cases, the performance difference is negligible.

One subtle point is that the order of property assignments is guaranteed to be the order written. If a property setter has side effects, such as logging or validation, the nested initializer will trigger those side effects in that order. This can be useful for deterministic initialization, but it also means you should avoid putting expensive or inconsistent logic in setters when using initializers.

When to Use a Factory Method Instead

If a nested object graph requires validation, default values, or conditional creation, a factory method often produces clearer code. For example:

csharp
public static Customer CreateWithAddress(string name, Address address) { return new Customer { Name = name, HomeAddress = address }; }

This separates the construction logic from the caller and allows you to add checks before the object is returned. A nested initializer is a declarative construct; it cannot contain if statements or loops. When you need logic, move to a method or a builder. The choice depends on whether the object graph is static or dynamic. For static graphs, initializers are concise; for dynamic graphs, imperative code is more maintainable.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.