3.1 - Classes and Objects
Classes and objects are the fundamental building blocks of object-oriented programming in C#. They form the core of how we structure and organize code in an object-oriented paradigm.
🧩 Visual Learning: Classes vs Objects
Think of the relationship between classes and objects like a blueprint and houses:
┌─ ──────────────────┐ ┌───────────────────┐
│ │ │ House #1 │
│ │ │ ┌─┐ │
│ │ │ ┌┘ └┐ ┌────┐ │
│ BLUEPRINT │ creates ────────┼─┘ └───┘ │ │
│ │ │ │ │
│ │ │ └─────────────┘ │
│ │ └───────────────────┘
│ │
│ │ ┌───────────────────┐
│ │ │ House #2 │
│ │ │ ┌─┐ │
│ │ │ ┌┘ └┐ ┌────┐ │
│ │ creates ────────┼─┘ └───┘ │ │
│ │ │ │ │
│ │ │ └─────────────┘ │
└───────────────────┘ └───────────────────┘
- The class is like a blueprint - it defines what all houses of this type will have
- The objects are like actual houses built from that blueprint - each one is separate but follows the same design
💡 Concept Breakdown: Classes and Objects
What is a Class?
A class is a blueprint or template that defines the structure and behavior of a particular type of object. It encapsulates:
- Data (fields and properties) that represents the state (what the object "knows")
- Methods that define the behavior (what the object can "do")
- Events that enable communication between objects
- Access modifiers that control visibility and encapsulation
What is an Object?
An object is an instance of a class that exists in memory during program execution. When you create an object, you're essentially creating a concrete realization of the class blueprint with its own unique state.
🔰 Beginner's Corner: Real-World Analogy
Think about a car manufacturing process:
-
The class is like the car design and manufacturing plans
- It specifies what properties all cars will have (color, model, engine size)
- It defines what all cars can do (accelerate, brake, turn)
- It establishes how the parts work together
-
Each object is like an individual car that rolls off the assembly line
- It has its own specific values for those properties (red color, sedan model, 2.0L engine)
- It can perform all the actions defined in the blueprint
- It exists as a real entity that can be used