Properties, fields and access control
Encapsulation protects an object’s state by controlling how callers access and change it. Fields store data. Properties expose accessor behavior with field-like syntax; methods can express actions that validate input and preserve an invariant.
using System;Bin bin = new Bin(4);Console.WriteLine(bin.Quantity);class Bin{ private readonly int quantity; public Bin(int n) { if (n < 0) throw new ArgumentOutOfRangeException(nameof(n)); quantity = n; } public int Quantity => quantity;}The public expression-bodied property exposes the value without a public setter.
Expected output (reasoned, not executed):
4Choose a public contract
private limits access to the declaring type’s implementation; public permits access wherever the containing type is accessible. internal generally limits access to the same assembly, while protected access supports derived types (chapter 10). An auto-property such as public int Quantity { get; private set; } has compiler-provided storage; outside callers can read but cannot set it. A getter-only property can calculate its value from a private field.
Protect every state transition
A nonnegative-stock invariant requires valid construction and valid later changes. TryRemove rejects a negative request or a request beyond available quantity before updating state. Returning false lets a caller handle ordinary refusal without exceptions. This model permits zero stock and zero-size removal. An auto-property with a private setter does not validate itself; the class’s methods must enforce the rule. Returning a mutable collection directly could expose another mutation path, a separate concern for later lessons.
using System;Bin bin = new Bin(5);Console.WriteLine(bin.TryRemove(3));Console.WriteLine(bin.Quantity);Console.WriteLine(bin.TryRemove(4));Console.WriteLine(bin.Quantity);class Bin{ public int Quantity { get; private set; } public Bin(int quantity) { if (quantity < 0) throw new ArgumentOutOfRangeException(nameof(quantity)); Quantity = quantity; } public bool TryRemove(int count) { if (count < 0 || count > Quantity) return false; Quantity -= count; return true; }}The successful call removes three; the rejected call leaves two unchanged. Both constructor and method protect the invariant.
Expected output (reasoned, not executed):
True2False2using System;Bin bin = new Bin(2);Console.WriteLine(bin.IsEmpty);bin.TryRemove(2);Console.WriteLine(bin.IsEmpty);Console.WriteLine(bin.TryRemove(-1));class Bin{ public int Quantity { get; private set; } public bool IsEmpty => Quantity == 0; public Bin(int quantity) { if (quantity < 0) throw new ArgumentOutOfRangeException(nameof(quantity)); Quantity = quantity; } public bool TryRemove(int count) { if (count < 0 || count > Quantity) return false; Quantity -= count; return true; }}IsEmpty is derived from current quantity, so it cannot become stale due to forgetting to update a separate boolean field. Negative removal is rejected.
Expected output (reasoned, not executed):
FalseTrueFalseCommon mistake and correction
A public setter such as public int Quantity { get; set; } permits arbitrary assignments unless the setter validates them. A private setter with a meaningful action narrows the mutation interface. Access modifiers are language-level access control, not a substitute for authorization checks in a service.
Try it yourself
Create a SeatPool with nonnegative initial Available, a private setter, and TryReserve(int count). Reject negative counts and counts above Available. Starting with 3, test reserve 0, 2, 2, -1, 1, and 1; record success and remaining capacity after each.
Next: Static members and instance members. Examples target C# 14 / net10.0. They are static study material; compiler and ByteMind execution have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Properties, fields and access control — knowledge check
Apply the lesson concepts to the following scenarios.
What is accessible to outside callers through public int Quantity { get; private set; }?
What is a field primarily used for?
Why check count < 0 in TryRemove?
What should a rejected removal do to Quantity?
Why calculate IsEmpty from Quantity?