11. Object Design and Composition#
An order and its line items form a collaborating model, not just a collection of individually correct classes. This chapter gives you the rules every later data structure depends on: how references are shared and copied, when two objects count as equal, and what a null reference means. You will then choose among classes, structs, records, and enums for business values, divide responsibility among an order, its lines, and its products, protect the order’s internal list, and test the collaboration through its public surface. Deeper nullability is a supporting reading in this same sequence.
References and identity: Trace when variables share one object, and define equality separately from identity with
EqualsandGetHashCode.Copying: Decide whether a copy shares inner objects (shallow) or owns its own (deep).
Structs, records, and enums: Choose copy behavior, value equality, and named choices for a business value.
Composition and ownership: Let each object calculate its own result and keep internal collections private.
Contracts and missing data: Test observable behavior, preserve state on rejected changes, and make optional data explicit.
Chapter Video
C# Programming Tutorial 10 - Value Types and Reference Types (8:12) by Caleb Curry.
Hosted on YouTube; property of its original creator, embedded here for educational reference only.
Focus on the difference between copying a value and sharing an object reference. The content sections extend this distinction to records, composition, and object contracts.
Learning Objectives
By the end of this chapter, you will be able to:
Trace how two variables can refer to one object, and predict which changes show through every alias for mutable and immutable types.
Distinguish identity from equality, test identity with
ReferenceEquals, and overrideEqualsandGetHashCodetogether so a business type works correctly as a dictionary key.Explain what a method can change through a reference it receives and why reassigning that parameter cannot affect the caller, and use
refandoutwhen a method must replace the caller’s variable.Write shallow and deep copies of an order that holds a list of order lines, show by running code which objects each copy shares, and diagnose a
NullReferenceException.Choose among a class, struct, record, record struct, and enum for a business value, explaining copy behavior, value equality,
withexpressions, and the mutable-struct trap.Design collaborating product, order-line, and order classes in which each object calculates its own result, and protect the order’s private list with a read-only view, defensive copies, and a
ToStringoverride.Test collaborating objects through their public surface with arrange, act, and assert, confirm that a rejected change preserves state, and refactor by extracting a method without changing the contract.
Supporting-reading outcome: enable nullable analysis, mark optional references with ?, check missing values with is null, ?., ??, and ??=, and use nullable value types such as int?.
Chapter Flow
Suggested three-meeting pace (115 minutes): read the relevant explanations and predict the selected example before class.
Meeting |
Minutes |
Guided focus |
|---|---|---|
1 |
40 |
11.1: references and aliases, identity versus equality with |
2 |
35 |
11.2: class versus struct copy behavior, records and |
3 |
40 |
11.3 and 11.4: has-a relationships, collection ownership and read-only views, arrange-act-assert checks, rejected changes, and refactoring without changing the contract. |
Class uses selected traces, runs, and checks. Use the remaining worked examples for practice and reference. Supporting readings are selected separately; lab and homework follow the core lessons.
Glossary
# |
Term |
Explanation |
|---|---|---|
1 |
Reference type |
A type, such as a class, whose variables hold a reference to an object rather than the object itself. |
2 |
Value type |
A type, such as |
3 |
Reference |
The value a class variable holds, which leads to an object in memory. |
4 |
Alias |
Another reference to the same object. |
5 |
Mutable |
Allowing observable state to change after construction. |
6 |
Immutable |
Keeping observable state fixed after construction. |
7 |
Identity |
Being the same runtime object, tested with |
8 |
Reference equality |
The default |
9 |
Value equality |
An equality rule that compares contents, such as two |
10 |
Hash code |
An |
11 |
|
A parameter that lets a method read and replace the caller’s variable. |
12 |
|
A parameter the method must assign, used to return an extra result as in the |
13 |
Shallow copy |
A new outer object whose reference fields still reach the same inner objects as the original. |
14 |
Deep copy |
A copy that also creates new inner objects, so the two copies share nothing that can change. |
15 |
Copy constructor |
A constructor that builds a new object from an existing one of the same type. |
16 |
Null reference |
A reference that reaches no object; using its members throws |
17 |
Struct |
A user-defined value type whose value is copied on assignment. |
18 |
Default value |
The value a struct or field has before any constructor runs, with every field zero or |
19 |
Record |
A class or struct with compiler-generated value equality, |
20 |
Record class |
A reference type declared with |
21 |
Record struct |
A value type declared with |
22 |
Readonly struct |
A struct whose fields cannot change after construction. |
23 |
|
An expression that copies a record and changes only the listed properties on the copy. |
24 |
Nondestructive mutation |
Producing a changed copy instead of changing the original. |
25 |
Deconstruction |
Unpacking a positional record into separate variables. |
26 |
Enum |
A type that names a fixed set of choices, such as order statuses. |
27 |
Transition policy |
Rules stating which next states an object may enter from its current state. |
28 |
Composition |
A has-a relationship in which one object holds others as parts or collaborators. |
29 |
Aggregation |
A has-a relationship in which the part can exist independently of the whole, such as a product shared by many order lines. |
30 |
Responsibility |
A coherent job assigned to a type, such as an order line calculating its own amount. |
31 |
Ownership |
A policy specifying which object may control or change a piece of state. |
32 |
Read-only view |
An |
33 |
Defensive copy |
A copy made to protect owned state from edits through another reference. |
34 |
Snapshot |
A saved view of values whose independence depends on its copying policy. |
35 |
Precondition |
A requirement a caller must meet before calling an operation. |
36 |
Postcondition |
A promise about the result and state after an operation succeeds. |
37 |
Invariant |
A rule preserved at public operation boundaries. |
38 |
Arrange, act, assert |
A test pattern: set up objects, perform one operation, then check the observable result. |
39 |
Refactoring |
Changing internal design while preserving intended behavior. |
40 |
Extract method |
A refactoring that moves repeated or complex code into a named method. |
41 |
Cohesion |
Keeping a related responsibility together in a type or operation. |
42 |
Coupling |
The dependence of one part of a program on another part’s details or promises. |
43 |
Nullable reference annotation |
A |
44 |
Null-coalescing operator |
The |
45 |
Null-conditional operator |
The |
46 |
Null-forgiving operator |
The |
47 |
Nullable value type |
A value type such as |