Backend in .NET · Chapter 2
Structs, records and boxing
About this chapter
C# gives a small piece of data four homes: a plain class, a record, a struct, or a record struct, and the choice changes how it is copied, compared and stored. Using a stock service, this chapter shows what each option gives and costs: copying and equality, what boxing does when a value type is stored as object, how generics avoid it, why records work as dictionary keys, and the surprises of shallow copies and of what a record prints about itself when one of its fields is a secret.
Who it is for: Developers learning C# for backend work who know classes and want to choose the right type for data and explain the choice in an interview.
You will be able to
- Pick the right declaration for a piece of data from class, record, struct and record struct.
- Explain boxing and unboxing and where a generic collection avoids them.
- Explain what lets a record work as a dictionary key and what can go wrong when a key changes.
- Predict what a shallow copy made with the with expression shares with the original.
- Avoid exposing a secret through the text a record prints about itself.
The key idea: Whether a type is copied or shared, and compared by identity or by content, is decided when it is declared. Choosing the declaration is choosing those behaviours, so the right answer depends on how the data will be used rather than on habit.
In this chapter
- Four ways to write a small piece of data
- Structs: what you get, and what you give up
- Records: value-like behaviour on a reference type
- Boxing and unboxing
- Generics make most boxing unnecessary
- Arrays and collections are reference types
- Records as keys, and the shallow with
- Three record details that matter in a backend
- What the compiler tells you
- Mistakes that recur
Locked: needs a plan
You can read chapter 1 free. Chapter 2 is the next one.
What you can do now, free: re-read chapter 1 and try its problems.
What a plan gives you: all chapters of the track you pick and their checks. Professional, one role is ₹329 a month or ₹2,299 a year. It renews until you cancel, and you can cancel any time. Paid plans open at launch.
Why is this locked?
Chapter 1 of every track is free, so you can see how the track reads. The rest of a track and its checks come with a plan, or open as you pass each chapter's check.
The price is for one period, a month or a year. A plan renews until you cancel.