Chapter 5: Holding a Class Responsible

In This Chapter

check.png Letting the class protect itself through access control

check.png Introducing the property, a specialized kind of method

check.png Allowing an object to initialize itself via the constructor

check.png Defining multiple constructors for the same class

check.png Constructing static or class 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, 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.

I don’t ...

Get C# 5.0 All-in-One For Dummies now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.