9. Classes#
Object-oriented programming begins with the class — a blueprint that bundles state and behavior together.
This chapter covers the first and most important OOP pillar: encapsulation — hiding data inside a class
and exposing only what’s needed. You’ll define classes, create instances, and build reusable types like Rational.
Why this chapter matters
Encapsulation is the most universally useful OOP principle — every serious C# program uses it. Organizing code around objects that own their data leads to programs that are easier to extend and reason about:
fields store the state an object needs to do its job
methods operate on that state, keeping implementation details private
constructors ensure objects start in a valid configuration
properties provide controlled access to private fields
Learning goals
By the end of this chapter, you should be able to:
define a class with fields, constructors, methods, and properties
apply encapsulation using
privatefields andpublicpropertiescreate and use instances of your own classes
implement a complete class such as
Rationalwith arithmetic operationsdistinguish between classes (reference types) and structs (value types)