Classes, Properties and Records
Learn to define classes with fields, properties and constructors, to use init-only properties, records and with-expressions, and see reference equality against value equality in real output.
In this lesson you will
- Write a class with properties
- Use constructors and init
- Use records for data
- Tell reference from value equality
About 28 minutes
A MenuItem is more than a string
Omar has a name, a price and a category for each item on his menu. Keeping three parallel arrays in step is painful, and an item should be one thing. A class is a blueprint, and an object is one thing made from it. In C# the data of an object is usually exposed through properties: members that look like fields from the outside and can run code when they are read or set. The short form, an auto-property such as public string Name { get; set; }, creates a hidden field for you.
An init-only property, written with init, can be set when the object is created and never afterwards, which gives you immutable objects with the object initializer syntax. The required modifier forces callers to provide a value. A record is a class designed for data: record MenuItem(string Name, decimal Price) gives you the constructor, properties, a readable ToString and, importantly, value equality, where two records with equal contents are equal. A with-expression copies a record with some changes, as in item with { Price = 3.30m }. Static members belong to the class and not to any object, and are used for counters and helpers.
| Feature | Meaning |
|---|---|
| Property | A field-like member with get and set code |
| init | Set once when creating the object |
| required | The caller must set it |
| record | A data class with value equality and with-expressions |
| static | Belongs to the class, shared by all objects |
var a = new Cup { Name = "flat white", Ml = 250 };
var b = new Cup { Name = "flat white", Ml = 250 };
var c = a;
c.Ml = 300;
Console.WriteLine($"a: {a}, b: {b}");
Console.WriteLine($"a == b: {a == b}, a.Equals(b): {a.Equals(b)}, a == c: {a == c}");
Console.WriteLine($"cups created: {Cup.Created}");
var x = new MenuItem("tea", 2.10m);
var y = new MenuItem("tea", 2.10m);
var z = x with { Price = 2.40m };
Console.WriteLine($"{x} | {z}");
Console.WriteLine($"x == y: {x == y}, ReferenceEquals(x, y): {ReferenceEquals(x, y)}, x == z: {x == z}");
Console.WriteLine($"price after tax at 19%: {x.Price * 1.19m:F2}");
Cup? none = null;
Console.WriteLine($"null cup name: {none?.Name ?? "no cup"}");
try { Console.WriteLine(none!.Name); }
catch (NullReferenceException) { Console.WriteLine("NullReferenceException caught"); }
class Cup
{
public static int Created { get; private set; }
public required string Name { get; init; }
public int Ml { get; set; }
public Cup() { Created++; }
public override string ToString() => $"{Name} {Ml}ml";
}
record MenuItem(string Name, decimal Price);
a: flat white 300ml, b: flat white 250ml
a == b: False, a.Equals(b): False, a == c: True
cups created: 2
MenuItem { Name = tea, Price = 2.10 } | MenuItem { Name = tea, Price = 2.40 }
x == y: True, ReferenceEquals(x, y): False, x == z: False
price after tax at 19%: 2.50
null cup name: no cup
NullReferenceException caught
Two cups were created, so the static counter says 2. The line “a: flat white 300ml, b: flat white 250ml” shows that c = a made c another name for the same object: changing c.Ml to 300 changed a, and left b, a separate object, at 250. For an ordinary class, == and Equals compare references, so a == b is false even though the two cups hold the same data, and a == c is true. A class can override this, but records do it for you.
The records behave differently. x and y are two separate objects with equal contents, and x == y is true while ReferenceEquals reports false: records have value equality. The with-expression made z, a copy of x with a new price, and the original is untouched, which is why records are a good fit for data that should not be changed in place. The ToString of a record lists its properties, here MenuItem { Name = tea, Price = 2.10 } and MenuItem { Name = tea, Price = 2.40 }, without any code from us. Adding 19 percent to a price of 2.10 gives 2.50 with decimal arithmetic. The 19 percent is only an example rate for this lesson, and real tax rates depend on your country and your goods.
The last lines use null. The null-conditional operator ?. returned null instead of failing, and ?? supplied the text “no cup”. The exclamation mark in none!.Name tells the compiler to stop warning, and the call then failed at run time with a NullReferenceException, the most common C# error. Lesson 17 shows how nullable reference types help the compiler find such problems before the program runs.
Check by hand: 2.10 x 1.19 = 2.499, which rounds to 2.50 with two decimals. Two cups were built with new, and c = a built none, so the counter is 2.
For plain classes, == compares references. Use records, or override Equals and GetHashCode, when you want equality by content.
Use init properties or records, and make a changed copy with with. Objects that never change are easy to share and reason about.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8. The required modifier needs C# 11 and records need C# 9.
Practice
Make a record Customer(string Name, string Email) and a class Order with a list of MenuItem values and a read-only Total property. Print an order, then create a changed copy of a customer with a with-expression.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is an auto-property?
- A static variable
- A method
- A file
- A property with a hidden field generated by the compiler
public string Name { get; set; }.
What does init allow?
- Setting it any time
- Reading only
- Setting a property only when the object is created
- Deleting it
It supports immutable objects.
Why was x == y true for records?
- They are the same object
- Their names match only
- Records compare by value
- C# is lenient
ReferenceEquals showed they are different objects.
What does a with-expression do?
- Deletes a record
- Copies a record with some changes
- Compares two records
- Sorts records
The original is unchanged.
What causes a NullReferenceException?
- Dividing by two
- Using a member on null
- Printing text
- Using a loop
Variable pointed at no object.
Summary
- Properties expose data; init and required control how objects are created.
- Classes compare by reference; records compare by value.
- with-expressions copy records with changes.
- null references throw NullReferenceException.
Questions
What is the difference between a field and a property?
A field stores data directly. A property is accessed like a field but can run code in its getter and setter and be controlled separately.
Should I use class or record?
Use record for data with value equality and little behaviour. Use class for objects with identity and behaviour.
What is a struct?
A value type for small data, copied on assignment. Use it for small, immutable pieces of data, and see the documentation for details.
