Chapter 5
Holding a Class Responsible
IN THIS CHAPTER
Protecting a class
Allowing an object to initialize itself
Defining multiple constructors for a class
Constructing static or class members
Working with expression-bodied members
A class must be held responsible for its actions. Just as a microwave oven shouldn’t burst into flames if you press the wrong key, so a class shouldn’t allow itself to roll over and die when presented with incorrect data.
To be held responsible for its actions, a class must ensure that its initial state is correct and then control its subsequent state so that it remains valid. C# provides both these capabilities.
Restricting Access to Class Members
Simple classes define all their members as public. Consider a BankAccount program that maintains a balance data member to retain the balance in each account. Making that data member public puts everyone on the honor system.
Most banks aren’t nearly so forthcoming as to leave a pile of money and a register for ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access