Lesson 13 of 24

In progress

Course progress

C# and .NET

Constructors and records

Validate in the constructor, chain with this, and use records for values that are defined by their data.

A constructor is the only place an object is set up before anyone can use it. C# adds records, which generate most of a correct value type for you.

What you will learn

  • Validate in the constructor so no invalid object exists.
  • Chain constructors with this(...).
  • Use records and with for immutable values.

A validating constructor

public class Email
{
public string Address { get; }
public Email(string address)
{
if (string.IsNullOrWhiteSpace(address) || !address.Contains('@'))
throw new ArgumentException("invalid email", nameof(address));
Address = address.Trim().ToLowerInvariant();
}
}

After this returns, Address is non-null, trimmed and contains an @. Every method can rely on that, which removes defensive checks from the rest of the class.

The exception names the parameter, so the stack trace points at the caller’s argument rather than at the object.

Chaining

public class Money
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
if (amount < 0) throw new ArgumentOutOfRangeException(nameof(amount));
Amount = amount;
Currency = currency;
}
public Money(decimal amount) : this(amount, "INR") { }
public static Money FromRupees(int rupees) => new(rupees, "INR");
}

this(...) calls the other constructor, so validation and normalisation live in one place. A static factory names the unit at the call site: Money.FromRupees(45) is unambiguous where new Money(45) is not.

Object initialisers and constructors

public class Customer
{
public required string Name { get; init; }
public string? Email { get; init; }
}
var customer = new Customer { Name = "Ana", Email = "ana@example.com" };

required plus init gives an object that is immutable after construction and cannot be created without its required parts. The constructor is implicit, and the compiler enforces the contract.

Use a constructor when there are rules between fields. Use required init when each field stands alone.

Records

public record Money(decimal Amount, string Currency);
var a = new Money(100m, "INR");
var b = new Money(100m, "INR");
Console.WriteLine(a == b);        // true, value equality
Console.WriteLine(a);             // Money { Amount = 100, Currency = INR }

A positional record generates:

  • A constructor with those parameters.
  • Public init properties.
  • Value-based Equals, GetHashCode and ==.
  • A readable ToString.
  • A deconstructor.

That is most of a value type, in one line. Records are the right choice for money, ranges, identifiers and anything else defined by its data.

Validation in records

public record Money(decimal Amount, string Currency)
{
public Money
{
if (Amount < 0) throw new ArgumentOutOfRangeException(nameof(Amount));
if (string.IsNullOrWhiteSpace(Currency))
throw new ArgumentException("currency required", nameof(Currency));
}
}

The compact constructor syntax validates positional parameters without repeating the assignments. It runs before the properties are set, so the object never exists with invalid data.

Non-destructive mutation

var original = new Money(100m, "INR");
var raised = original with { Amount = 120m };
Console.WriteLine(original.Amount);   // 100
Console.WriteLine(raised.Amount);     // 120

with copies the record and replaces the listed properties. The original is untouched, which is what makes records safe to share. For a deeply nested record, with is a shallow copy: a nested reference is shared unless it is replaced.

Record structs and classes

public readonly record struct Point(double X, double Y);

A record struct is a value type with the same generated members. Use it for small values that are copied often, where an allocation per instance would matter. A record class is the default and the safer choice.

Mutable classes and identity

A class with a mutable state and an id is an entity. Two customers with the same name are still different customers, so value equality would be wrong.

public class Customer
{
public int Id { get; }
public string Name { get; set; }
public Customer(int id, string name)
{
Id = id;
Name = name;
}
}

The default reference equality is correct here: two objects are the same customer only if they are the same object. Do not add value equality to an entity unless you compare by id, and even then the id must be set.

Constructors that do work

public Customer(string name) : this(0, name) { }

Avoid constructors that open files, call a network or start threads. They can fail halfway, they make the class hard to test, and they publish a half-built object. Constructors should validate and assign; do the I/O in a factory method that returns a result. A factory can return null, a result object or a typed exception, which gives the caller options a constructor cannot. That keeps construction cheap and predictable, and it is the difference between a constructor and a factory in one sentence.

Initialising a collection property with = new() and also assigning it in the constructor, so the earlier list is discarded. It is not a bug, but it is a wasted allocation and a sign the initialisation is duplicated.

Create a Temperature record with a value and a unit, validating that the unit is C or F and that the value is above absolute zero. Show that with produces a new value without changing the original.

Show solution
public record Temperature(double Value, char Unit) { public Temperature { if (Unit is not ('C' or 'F')) throw new ArgumentException("unit must be C or F", nameof(Unit)); double celsius = Unit == 'C' ? Value : (Value - 32) * 5 / 9; if (celsius < -273.15) throw new ArgumentOutOfRangeException(nameof(Value), "below absolute zero"); } } var freezing = new Temperature(0, 'C'); var warmer = freezing with { Value = 25 }; Console.WriteLine(freezing); // Temperature { Value = 0, Unit = C } Console.WriteLine(warmer);

The compact constructor validates both fields, converting to Celsius only for the absolute-zero check. with returns a new record, so freezing is unchanged, which is the property that makes records safe to pass around.

Recap

  • Validate in the constructor and keep properties init-only where possible.
  • A record gives value equality, ToString and with for one line of code.
  • Use mutable classes for entities, where reference identity is the correct equality.

Next, properties: getters, setters and the logic that belongs in them.

Can a record be inherited?
Yes, records can inherit from other records, and equality accounts for the runtime type.
Do records allocate more?
They are classes unless declared as record structs, so the allocation is the same as any object.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.