Skip to content

C# Object Construction, Initialization and Properties

This page covers how a C# object comes into existence and how its state is exposed afterward. It answers three practical questions. How do I declare state without boilerplate (auto-implemented, computed, validated, lazy and field-backed properties, indexers)? How do I make sure an object is fully and correctly initialized (target-typed new, init, required, primary constructors)? And how do I change an immutable object or split a type between handwritten and generated code (with expressions, partial properties, events and constructors)?

All samples use one invented domain, an OrdersPortal application with customers, orders and order lines. Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). The output shown was produced with SDK 10.0.115.

Feature Version Use it when
Auto-implemented properties C# 3 A property just stores a value.
Computed properties C# 1 pattern, => form C# 6 A value can be derived from other state.
Validated properties C# 1 pattern A setter must reject bad input.
Field-backed properties C# 14 You need a little logic in an accessor but no hand-written field.
Lazy properties C# 1 pattern, Lazy<T> .NET Framework 4 A value is expensive and may never be read.
Indexers C# 1 The object is naturally looked up by key or position.
Target-typed new C# 9 The type is already written on the left or in the parameter.
Init-only setters C# 9 Callers set values once, in an object initializer.
Required members C# 11 Some members must always be set by the caller.
With expressions C# 9 (records), C# 10 (structs, anonymous types) You need a modified copy of an immutable value.
Primary constructors C# 12 (classes and structs) Constructor parameters only feed fields or dependencies.
Partial properties C# 13 A source generator implements a property you declare.
Partial events C# 14 A generator or second file supplies event accessors.
Partial constructors C# 14 A generator or second file supplies the constructor body.

Introduced in C# 3 (.NET Framework 3.5). An auto-implemented property such as public int Id { get; set; } tells the compiler to generate a private backing field and trivial accessors, so you get the encapsulation of a property (binary-compatible changes later, data binding, serialization) without writing the field yourself. C# 6 added property initializers (= "") and get-only auto-properties, which can be assigned only in a constructor or initializer. Accessors can have different accessibility, for example private set, so a type can change a value internally while callers can only read it.

Auto-properties are the default shape for data-carrying classes, DTOs and view models. Reach for one of the other property styles on this page only when a property needs behavior.

var customer = new Customer { Id = 42, Name = "Harbor Supplies" };
customer.Name = "Harbor Supplies Ltd";
Console.WriteLine($"{customer.Id}: {customer.Name}, tier {customer.Tier}");
Console.WriteLine($"Created {customer.CreatedUtc:yyyy-MM-dd}");
public class Customer
{
public int Id { get; set; } // C# 3: compiler-generated backing field
public string Name { get; set; } = ""; // C# 6: property initializer
public string Tier { get; private set; } = "Standard";
public DateTime CreatedUtc { get; } = // C# 6: get-only auto-property
new(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
}

Output:

42: Harbor Supplies Ltd, tier Standard
Created 2026-11-01

Pitfalls:

  • A public set on every property makes any object mutable from anywhere; prefer init, private set or get-only where callers should not change state.
  • Non-nullable string auto-properties without an initializer trigger nullable warnings (CS8618). Initialize them, make them required, or set them in a constructor.

A pattern available since C# 1 (.NET Framework 1.0); the concise expression-bodied form public decimal LineTotal => ... arrived in C# 6. A computed property has a getter and no stored state: it derives its value from other members every time it is read. Because nothing is cached, the value can never go stale when the inputs change, which removes a whole class of synchronization bugs.

Use a computed property when the calculation is cheap, has no side effects and needs no parameters. Callers expect property reads to be fast and repeatable; if the work queries a database, allocates heavily or can throw for ordinary reasons, expose a method such as CalculateTotal() instead, or cache the result with a lazy property.

var line = new OrderLine { Sku = "PEN-01", UnitPrice = 2.50m, Quantity = 4, DiscountPercent = 10 };
Console.WriteLine($"{line.Sku}: {line.Quantity} x {line.UnitPrice} = {line.LineTotal} (bulk: {line.IsBulk})");
line.Quantity = 12; // no cached total to invalidate
Console.WriteLine($"{line.Sku}: {line.Quantity} x {line.UnitPrice} = {line.LineTotal} (bulk: {line.IsBulk})");
public class OrderLine
{
public string Sku { get; set; } = "";
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
public decimal DiscountPercent { get; set; }
// Computed (derived) properties: no stored state, recalculated on every read.
public decimal LineTotal => Math.Round(UnitPrice * Quantity * (1 - DiscountPercent / 100m), 2);
public bool IsBulk => Quantity >= 10;
}

Output:

PEN-01: 4 x 2.50 = 9.00 (bulk: False)
PEN-01: 12 x 2.50 = 27.00 (bulk: True)

Pitfalls:

  • Serializers usually write get-only computed properties to JSON; mark them [JsonIgnore] if the derived value should not be part of the contract.
  • A computed property that walks a large collection is O(n) per read; calling it inside a loop makes the loop O(n²).

A pattern available since C# 1 (.NET Framework 1.0). A validated property uses a manual backing field and a setter that checks the incoming value before storing it, throwing when the value would break the object’s invariants. The guard helpers added in .NET 8, such as ArgumentOutOfRangeException.ThrowIfNegativeOrZero and ThrowIfGreaterThan, keep these checks to one line and produce consistent exception messages with the parameter name and actual value.

Setter validation protects objects that stay mutable after construction. For values that must always be valid, validate in the constructor as well, as the sample does for Sku, otherwise a freshly created object can already be invalid. In C# 14 you can drop the manual field and write the same check with a field-backed property.

var line = new OrderLine("PEN-01") { Quantity = 3 };
Console.WriteLine($"{line.Sku} quantity {line.Quantity}");
try
{
line.Quantity = 0;
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName} = {ex.ActualValue}");
}
Console.WriteLine($"Still {line.Quantity}");
public class OrderLine
{
private int _quantity = 1;
public OrderLine(string sku)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sku); // constructor guards the invariant up front
Sku = sku;
}
public string Sku { get; }
public int Quantity
{
get => _quantity;
set
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value);
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 500);
_quantity = value;
}
}
}

Output:

PEN-01 quantity 3
Rejected: value = 0
Still 3

Pitfalls:

  • Validation in a setter does not run for the default value of the backing field or for a property initializer; make sure the initial state is valid too.
  • Throwing from setters is fine for programming errors; for user input that is expected to be wrong, validate before assignment and return errors instead of using exceptions for flow control.

Introduced in C# 14 (.NET 10). Inside a property accessor, the contextual keyword field refers to a backing field that the compiler synthesizes for you. You can keep one accessor automatic (get;) and give the other a body, so trimming, normalizing, validating or raising change notifications no longer forces you to declare a private field and write both accessors by hand. You can declare a body for one or both accessors.

The feature was available as a preview in C# 13 and is fully supported from C# 14. It also works in init accessors and in lazy getters such as get => field ??= Load();.

var contact = new CustomerContact();
contact.Email = " Sales@Harbor-Supplies.example ";
Console.WriteLine($"[{contact.Email}]");
contact.DisplayName = "Harbor Supplies";
contact.DisplayName = "Harbor Supplies"; // same value: no second notification
try
{
contact.Email = null!;
}
catch (ArgumentNullException)
{
Console.WriteLine("Null email rejected");
}
public class CustomerContact
{
// 'field' is the compiler-synthesized backing field (C# 14).
public string Email
{
get;
set => field = value?.Trim().ToLowerInvariant()
?? throw new ArgumentNullException(nameof(value));
} = "";
public string DisplayName
{
get;
set
{
if (field == value) return;
field = value;
Console.WriteLine($"DisplayName changed to '{value}'");
}
} = "";
}

Output:

[sales@harbor-supplies.example]
DisplayName changed to 'Harbor Supplies'
Null email rejected

Pitfalls:

  • A property initializer such as = " X " assigns the backing field directly and does not run your setter, so the initial value is not trimmed or validated.
  • In a type that already has a member named field, the keyword now wins inside accessors. Use @field or this.field for the old member, or rename it, when you upgrade to C# 14.

A pattern available since C# 1 (.NET Framework 1.0). A lazy property defers expensive work until the first read and then caches the result, so objects stay cheap to create and the cost is paid only if the value is used. There are three common implementations. Lazy<T>, added in .NET Framework 4, is thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication), so the factory runs once even under concurrent reads. A null-coalescing cache with ??= (C# 8), written against a manual field or, in C# 14, against field, is shorter but not thread-safe. For shared static values, a static readonly field initialized by the runtime is often simpler still.

var report = new MonthlySalesReport(() =>
{
Console.WriteLine(" (querying order totals...)");
return [120.00m, 80.00m, 45.50m];
});
Console.WriteLine("Report object created");
Console.WriteLine($"Total: {report.Total}");
Console.WriteLine($"Total again: {report.Total}");
Console.WriteLine($"Region: {report.Region}");
public class MonthlySalesReport
{
private readonly Lazy<decimal> _total;
public MonthlySalesReport(Func<decimal[]> loadOrderTotals)
{
// Thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication).
_total = new Lazy<decimal>(() => loadOrderTotals().Sum());
}
public decimal Total => _total.Value;
// Single-threaded alternative: cache in the backing field on first read.
public string Region => field ??= LoadRegion();
private static string LoadRegion()
{
Console.WriteLine(" (loading region...)");
return "EMEA";
}
}

Output:

Report object created
(querying order totals...)
Total: 245.50
Total again: 245.50
(loading region...)
Region: EMEA

Pitfalls:

  • If a Lazy<T> factory throws, the default mode caches the exception and rethrows it on every later read; use LazyThreadSafetyMode.PublicationOnly if retries should be possible.
  • field ??= Load() can run Load more than once when several threads read at the same time, and it only works for reference or nullable types.

Introduced in C# 1 (.NET Framework 1.0). An indexer is a property declared as this[...] that lets callers use array syntax on your object, for example cart["PEN-01"]. Indexers can take any parameter types and more than one parameter, can be overloaded (by string key and by int position, for example), and can be get-only. Since C# 8, a type with an int indexer and a Count or Length property also supports the ^ index operator automatically; see the index operator on the collections page. C# 13 added partial indexers alongside partial properties.

Use an indexer when lookup by key or position is the main way the object is used, and document what happens for a missing key: throw, return a default, or create an entry.

var cart = new ShoppingCart();
cart["PEN-01"] = 3;
cart["pad-02"] = 1;
cart["pen-01"] += 2; // case-insensitive key, get then set
cart["PAD-02"] = 0; // zero removes the line
Console.WriteLine($"PEN-01: {cart["PEN-01"]}, MUG-09: {cart["MUG-09"]}, lines: {cart.LineCount}");
public class ShoppingCart
{
private readonly Dictionary<string, int> _quantities = new(StringComparer.OrdinalIgnoreCase);
public int LineCount => _quantities.Count;
// Indexer: missing SKUs read as 0 instead of throwing KeyNotFoundException.
public int this[string sku]
{
get => _quantities.TryGetValue(sku, out int quantity) ? quantity : 0;
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
if (value == 0) _quantities.Remove(sku);
else _quantities[sku] = value;
}
}
}

Output:

PEN-01: 5, MUG-09: 0, lines: 1

Pitfalls:

  • cart["PEN-01"] += 2 calls the getter and then the setter; side effects in either accessor run on each compound assignment.
  • Returning a default for missing keys hides typos; when a miss is a bug, throw KeyNotFoundException or offer a TryGet method instead.

Introduced in C# 9 (.NET 5). When the compiler already knows the type an expression must produce, you can write new() or new(args) without repeating the type name. The target type can come from a variable declaration, a field or property declaration, a parameter, a return statement or a collection initializer. It is most valuable when the type name is long or generic, such as Dictionary<string, List<OrderLine>>, and in field declarations where var is not allowed.

Target-typed new and var solve the same duplication from opposite sides: var drops the type on the left, new() drops it on the right. Pick one consistently per codebase.

Dictionary<string, List<OrderLine>> linesByOrder = new(); // type named once, on the left
linesByOrder["SO-1001"] = new() { new("PEN-01", 3) }; // target: List<OrderLine>, then OrderLine
OrderLine extra = new("PAD-02", 1);
linesByOrder["SO-1001"].Add(extra);
PrintLine(new("MUG-09", 2)); // target: the parameter type
foreach (var line in linesByOrder["SO-1001"])
PrintLine(line);
static void PrintLine(OrderLine line) => Console.WriteLine($"{line.Sku} x {line.Quantity}");
public record OrderLine(string Sku, int Quantity);

Output:

MUG-09 x 2
PEN-01 x 3
PAD-02 x 1

Pitfalls:

  • PrintLine(new("MUG-09", 2)) hides the type at the call site, and adding an overload of PrintLine with another parameter type can make the call ambiguous.
  • It needs a target: var x = new(); does not compile, and new() against an interface type is an error.

Introduced in C# 9 (.NET 5). An init accessor is a setter that can run only during object creation: in an object initializer, a with expression, a constructor of the type, or another init accessor. After that, the property is read-only, and assignment is error CS8852. This gives you the readable object-initializer syntax of mutable classes together with the safety of immutability, without writing a constructor that takes every property.

An init accessor can have a body, so it can normalize or validate, and in C# 14 it can use field. Records use init for the properties generated from their positional parameters.

var address = new ShippingAddress
{
Street = "12 Dock Road",
City = "Portsmouth",
CountryCode = "gb",
};
// address.City = "Leeds"; // error CS8852: init-only property can only be assigned in an object initializer
Console.WriteLine(address);
public class ShippingAddress
{
public string Street { get; init; } = "";
public string City { get; init; } = "";
// An init accessor can still have a body.
public string CountryCode
{
get;
init => field = value.ToUpperInvariant();
} = "";
public override string ToString() => $"{Street}, {City}, {CountryCode}";
}

Output:

12 Dock Road, Portsmouth, GB

Pitfalls:

  • init stops reassignment of the property, not mutation of the object it refers to: an init-only List<OrderLine> can still be added to. Use IReadOnlyList<T> or immutable collections for deep immutability.
  • init does not force the caller to set anything; combine it with required when a value is mandatory.

Introduced in C# 11 (.NET 7). The required modifier on a property or field makes the compiler insist that every object creation sets that member, in an object initializer or through a constructor attributed with [SetsRequiredMembers]. Missing one is a compile-time error (CS9035), not a runtime surprise. It pairs naturally with init: the caller must set the value, and nobody can change it afterward.

required replaces the old trade-off between long constructors (safe but noisy) and object initializers (readable but easy to leave half-filled). It also gives the nullable analysis a guarantee, so a required string property does not need a dummy = "" initializer.

using System.Diagnostics.CodeAnalysis;
var fromInitializer = new OrderRequest { CustomerId = "C-100", Currency = "EUR" };
var fromConstructor = new OrderRequest("C-200", "GBP") { Notes = "Gift wrap" };
// var invalid = new OrderRequest { Currency = "EUR" };
// error CS9035: Required member 'OrderRequest.CustomerId' must be set in the object initializer or attribute constructor.
Console.WriteLine($"{fromInitializer.CustomerId} / {fromInitializer.Currency} / '{fromInitializer.Notes}'");
Console.WriteLine($"{fromConstructor.CustomerId} / {fromConstructor.Currency} / '{fromConstructor.Notes}'");
public class OrderRequest
{
public required string CustomerId { get; init; }
public required string Currency { get; init; }
public string Notes { get; init; } = "";
public OrderRequest() { }
[SetsRequiredMembers] // tells the compiler this constructor sets every required member
public OrderRequest(string customerId, string currency)
{
CustomerId = customerId;
Currency = currency;
}
}

Output:

C-100 / EUR / ''
C-200 / GBP / 'Gift wrap'

Pitfalls:

  • [SetsRequiredMembers] is a promise the compiler does not verify; if that constructor forgets a member, the object is created incomplete.
  • required is enforced by the C# compiler only. Reflection, Activator.CreateInstance and older serializers can still create objects without the values; System.Text.Json honors required from .NET 7.

Introduced in C# 9 (.NET 5) for records; C# 10 (.NET 6) extended it to structs, record structs and anonymous types. original with { Status = OrderStatus.Submitted } creates a copy of original and then applies the listed assignments to the copy, leaving the original untouched. This is non-destructive mutation: the standard way to “change” an immutable value. The assignments can target init and set properties and fields.

For records, the copy is made by a compiler-generated copy constructor that you can override; for structs it is a plain value copy. Either way the copy is shallow: reference-type members are shared between the original and the copy.

var draft = new Order("SO-1001", "C-100", OrderStatus.Draft, [new OrderLine("PEN-01", 3)]);
var submitted = draft with { Status = OrderStatus.Submitted };
Console.WriteLine($"draft: {draft.Status}, submitted: {submitted.Status}");
Console.WriteLine($"Same Lines list: {ReferenceEquals(draft.Lines, submitted.Lines)}");
submitted.Lines.Add(new OrderLine("PAD-02", 1)); // shallow copy: both see this
Console.WriteLine($"draft now has {draft.Lines.Count} lines");
var point = new GeoPoint(50.80, -1.09); // structs: C# 10
var moved = point with { Longitude = -1.10 };
Console.WriteLine(moved);
var summary = new { Number = "SO-1001", Total = 7.50m }; // anonymous types: C# 10
Console.WriteLine(summary with { Total = 9.00m });
public enum OrderStatus { Draft, Submitted, Shipped }
public record OrderLine(string Sku, int Quantity);
public record Order(string Number, string CustomerId, OrderStatus Status, List<OrderLine> Lines);
public readonly record struct GeoPoint(double Latitude, double Longitude);

Output:

draft: Draft, submitted: Submitted
Same Lines list: True
draft now has 2 lines
GeoPoint { Latitude = 50.8, Longitude = -1.1 }
{ Number = SO-1001, Total = 9.00 }

Pitfalls:

  • The copy is shallow, so mutable collections inside a record are shared, as the sample shows. Use immutable collections or copy the list explicitly in the with expression.
  • with bypasses constructor validation, because it does not call your primary or explicit constructor; put invariants in init accessors if copies must be checked too.

Introduced in C# 12 (.NET 8) for classes and structs; records have had positional primary constructors since C# 9. Parameters declared after the type name, class OrderPricingService(ITaxPolicy taxPolicy, decimal discountThreshold), are in scope in the whole type body: in member initializers, methods and properties. The compiler captures a parameter into a hidden field only when a member other than an initializer uses it.

Unlike records, a class or struct primary constructor does not create public properties. That makes it a good fit for dependency injection in services and controllers, where parameters are only used internally. Any other constructor must chain to the primary one with : this(...).

var pricing = new OrderPricingService(new FlatTaxPolicy(0.20m), discountThreshold: 100m);
Console.WriteLine(pricing.Total(80m));
Console.WriteLine(pricing.Total(150m));
Console.WriteLine(pricing.Describe());
public interface ITaxPolicy
{
decimal Rate { get; }
}
public record FlatTaxPolicy(decimal Rate) : ITaxPolicy; // record: parameters become public properties
// Class primary constructor (C# 12): parameters are in scope for the whole body,
// but they are NOT properties. The compiler captures them only where used.
public class OrderPricingService(ITaxPolicy taxPolicy, decimal discountThreshold)
{
public decimal Total(decimal subtotal)
{
decimal discounted = subtotal >= discountThreshold ? subtotal * 0.95m : subtotal;
return Math.Round(discounted * (1 + taxPolicy.Rate), 2);
}
public string Describe() => $"Tax {taxPolicy.Rate:0%}, 5% off from {discountThreshold}";
}

Output:

96.00
171.00
Tax 20%, 5% off from 100

Pitfalls:

  • Captured parameters are not readonly; any member can reassign them. If that matters, assign the parameter to a private readonly field and use the field.
  • Using a parameter both to initialize a property and inside a method stores the value twice and draws warning CS9124, after which the two copies can diverge.

Introduced in C# 13 (.NET 9). A partial property has a declaring declaration, which looks like an auto-property, public partial string Name { get; set; }, and an implementing declaration in another part of the same partial type that supplies the accessor bodies. Both declarations must have the same type, modifiers and accessors. Partial indexers work the same way.

The feature exists for source generators. You write the declaration with a marker attribute, and the generator emits the implementation, for example change notification for a view model or a cached Regex from [GeneratedRegex], which supports partial properties since .NET 9. Before C# 13 such generators had to work on fields and generate the property, which made the public API invisible in your own code.

using System.ComponentModel;
var customer = new CustomerViewModel();
customer.PropertyChanged += (_, e) => Console.WriteLine($"PropertyChanged: {e.PropertyName}");
customer.Name = "Harbor Supplies";
customer.Name = "Harbor Supplies"; // unchanged: no event
Console.WriteLine($"Name = {customer.Name}");
// CustomerViewModel.cs: the part you write (the declaring declaration).
public partial class CustomerViewModel
{
public partial string Name { get; set; }
}
// CustomerViewModel.g.cs: the part a source generator would emit (the implementing declaration).
public partial class CustomerViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public partial string Name
{
get => field ?? "";
set
{
if (field == value) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
}

Output:

PropertyChanged: Name
Name = Harbor Supplies

Pitfalls:

  • The implementing declaration cannot be auto-property syntax (get; set; with no bodies), because the compiler could not tell it from the declaring one. It must implement at least one accessor, and it can use field, as above.
  • Partial properties are rarely worth it in hand-written code: splitting a property across files makes it harder to find. Keep them for generator boundaries.

Introduced in C# 14 (.NET 10). An event can now be partial. The defining declaration uses field-like syntax, public partial event EventHandler<string>? Shipped;, and the implementing declaration, in another part of the partial type, must provide add and remove accessors. There is exactly one of each.

This completes the set of partial members for generator scenarios. A generator can implement weak-event subscriptions, logging, or interop event wiring while your file declares the event in plain sight. As with partial properties, the declaration and implementation must match in type and modifiers. Because the implementing declaration has custom accessors, the class raises the event through its own delegate field, _shipped in the sample, not through the event name.

var monitor = new OrderMonitor();
EventHandler<string> notify = (_, number) => Console.WriteLine($"Shipped: {number}");
monitor.Shipped += notify;
monitor.Ship("SO-1001");
monitor.Shipped -= notify;
monitor.Ship("SO-1002");
// OrderMonitor.cs: the defining declaration uses field-like event syntax.
public partial class OrderMonitor
{
public partial event EventHandler<string>? Shipped;
public void Ship(string orderNumber) => _shipped?.Invoke(this, orderNumber);
}
// OrderMonitor.Events.g.cs: the implementing declaration supplies add and remove.
public partial class OrderMonitor
{
private EventHandler<string>? _shipped;
public partial event EventHandler<string>? Shipped
{
add
{
Console.WriteLine("subscriber added");
_shipped += value;
}
remove
{
Console.WriteLine("subscriber removed");
_shipped -= value;
}
}
}

Output:

subscriber added
Shipped: SO-1001
subscriber removed

Pitfalls:

  • Custom add and remove are not thread-safe by default; field-like events use an atomic compare-exchange, so a generator that writes accessors by hand must do the same if subscriptions can race.
  • Raising the event by name (Shipped?.Invoke(...)) does not compile once accessors are custom; invoke the backing delegate.

Introduced in C# 14 (.NET 10). An instance constructor can be split into a defining declaration with no body, public partial OrderSnapshot(string number, int lineCount);, and an implementing declaration that provides the body. Only the implementing declaration may include a constructor initializer, : this(...) or : base(...), and only one part of the type can use primary-constructor syntax.

The typical use is interop and code generation: your file declares the constructor signature that the rest of the code calls, and a generator writes the body, for example to initialize generated fields or native handles. Static constructors cannot be partial.

var snapshot = new OrderSnapshot("SO-1001", 3);
Console.WriteLine($"{snapshot.Number}: {snapshot.LineCount} lines, captured {snapshot.CapturedBy}");
try
{
_ = new OrderSnapshot("", 1);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName}");
}
// OrderSnapshot.cs: the defining declaration (no body).
public partial class OrderSnapshot
{
public partial OrderSnapshot(string number, int lineCount);
public string Number { get; }
public int LineCount { get; }
public string CapturedBy { get; private set; } = "";
}
// OrderSnapshot.g.cs: the implementing declaration; only this part may use : this(...) or : base(...).
public partial class OrderSnapshot
{
public partial OrderSnapshot(string number, int lineCount) : base()
{
ArgumentException.ThrowIfNullOrEmpty(number);
Number = number;
LineCount = lineCount;
CapturedBy = "generated constructor";
}
}

Output:

SO-1001: 3 lines, captured generated constructor
Rejected: number

Pitfalls:

  • The generated body is out of sight; put validation callers depend on in the part you own, or document it clearly in the declaration.
  • Accessibility, modifiers and parameter types must match between the two declarations; mismatched parameter names compile but draw a warning, and the emitted names come from the defining declaration.
  • Storing state: start with an auto-property. Add field (C# 14) when you need a little logic; fall back to a manual field only when several members share it.
  • Derived state: a computed property if it is cheap, a lazy property if it is expensive and stable, a method if it takes parameters or can fail.
  • Mandatory values: required plus init for data objects built with initializers; a constructor (primary or explicit) when values must be validated together or when dependencies are injected.
  • Immutable updates: init properties on records or record structs, changed with with.
  • Partial members: only at a source-generator boundary. Ordinary code should keep a member in one place.

What is the difference between init and required? init controls when a property can be assigned: only during creation. required controls whether it must be assigned: the compiler rejects any creation that omits it. They answer different questions, so data types often use both: public required string CustomerId { get; init; }.

Does a with expression call the constructor? No. For a record it calls the compiler-generated copy constructor (which you can override), then applies the assignments through init or set accessors. Validation in the primary constructor does not run, and the copy is shallow, so reference-type members are shared.

Why might a class primary constructor parameter differ from the property you initialized with it? If a parameter initializes a property and is also used in a method, the compiler captures the parameter in a hidden field and the property has its own backing field. Changing the property later does not change the captured parameter. The compiler warns with CS9124; the fix is to use only one of them.

When should a property be a method instead? When it is expensive, has side effects, can fail for normal reasons, returns a new copy each time, or needs parameters. Callers, debuggers and serializers all treat property reads as cheap and safe to repeat.

What does the field keyword change compared with a manual backing field? It removes the field declaration and the trivial accessor, and keeps the field private to the property, so no other member can bypass the setter logic. The trade-offs are that property initializers bypass the setter and that existing members named field need @field after upgrading.

Senior scenario: an OrdersPortal team is adding required to its public request DTOs. What can go wrong? Adding required to an existing public type is a source-breaking change for every consumer that creates it without setting those members, and it changes nothing for code compiled earlier. Serializers and object mappers must understand it: System.Text.Json enforces required from .NET 7 and throws a JsonException for missing JSON properties, which can turn previously accepted requests into 400 responses. Roll it out with a major version or new DTO types, add [SetsRequiredMembers] only to constructors that truly set everything, and test deserialization paths, not just compilation.