Classes and Objects
Object-Oriented Programming (OOP) is a way of organizing code around "objects" that contain data and behavior. This lesson introduces the fundamental concepts of classes and objects.
What is a Class?
A class is a blueprint or template for creating objects. It defines:
- What data the object will hold (fields/properties)
- What actions the object can perform (methods)
csharp1// A class definition - the blueprint2class Dog3{4 public string Name;5 public int Age;67 public void Bark()8 {9 Console.WriteLine($"{Name} says: Woof!");10 }11}
What is an Object?
An object is an instance of a class - a specific realization of the blueprint.
csharp1// Creating objects from the Dog class2Dog myDog = new Dog();3myDog.Name = "Buddy";4myDog.Age = 3;5myDog.Bark(); // Output: Buddy says: Woof!67Dog anotherDog = new Dog();8anotherDog.Name = "Max";9anotherDog.Age = 5;10anotherDog.Bark(); // Output: Max says: Woof!
Each object has its own copy of the data but shares the same behavior.
The new Keyword
Use new to create an instance of a class:
csharp1// Creating an object2ClassName objectName = new ClassName();34// Examples5Dog pet = new Dog();6Car myCar = new Car();7Person user = new Person();
Class Definition Syntax
csharp1class ClassName2{3 // Fields (data)4 public int field1;5 public string field2;67 // Properties (covered next lesson)8 public int Property { get; set; }910 // Methods (behavior)11 public void DoSomething()12 {13 // Method body14 }15}
A Complete Example
csharp1// Define the class2class Person3{4 public string FirstName;5 public string LastName;6 public int Age;78 public void Introduce()9 {10 Console.WriteLine($"Hi, I'm {FirstName} {LastName}, age {Age}.");11 }1213 public void HaveBirthday()14 {15 Age++;16 Console.WriteLine($"Happy birthday! {FirstName} is now {Age}.");17 }18}1920// Use the class21Person person1 = new Person();22person1.FirstName = "Alice";23person1.LastName = "Smith";24person1.Age = 25;2526Person person2 = new Person();27person2.FirstName = "Bob";28person2.LastName = "Jones";29person2.Age = 30;3031person1.Introduce(); // Hi, I'm Alice Smith, age 25.32person2.Introduce(); // Hi, I'm Bob Jones, age 30.3334person1.HaveBirthday(); // Happy birthday! Alice is now 26.
Why Use Classes?
1. Organization
Group related data and behavior together.
csharp1// Without classes - loose variables2string playerName = "Hero";3int playerHealth = 100;4int playerScore = 0;56// With a class - organized7class Player8{9 public string Name;10 public int Health;11 public int Score;12}
2. Reusability
Create multiple objects from one class.
csharp1Player player1 = new Player { Name = "Hero", Health = 100 };2Player player2 = new Player { Name = "Villain", Health = 150 };
3. Encapsulation
Hide internal details and expose a clean interface.
csharp1class BankAccount2{3 private decimal balance; // Hidden from outside45 public void Deposit(decimal amount)6 {7 if (amount > 0)8 balance += amount;9 }1011 public decimal GetBalance() => balance;12}
4. Modeling Real-World Entities
Represent things from the problem domain.
csharp1class Book2{3 public string Title;4 public string Author;5 public int Pages;6}78class Car9{10 public string Make;11 public string Model;12 public int Year;13}
Object Initialization Syntax
Traditional Way
csharp1Person p = new Person();2p.FirstName = "Alice";3p.LastName = "Smith";4p.Age = 25;
Object Initializer Syntax
csharp1Person p = new Person2{3 FirstName = "Alice",4 LastName = "Smith",5 Age = 256};
Target-Typed new (C# 9+)
csharp1Person p = new()2{3 FirstName = "Alice",4 LastName = "Smith",5 Age = 256};
Classes in Separate Files
For larger projects, put each class in its own file:
Person.cs
csharp1public class Person2{3 public string Name;4 public int Age;5}
Program.cs
csharp1Person p = new Person();2p.Name = "Alice";
Reference Types
Classes are reference types. Variables hold a reference to the object, not the object itself.
csharp1Person a = new Person { Name = "Alice" };2Person b = a; // b points to the SAME object as a34b.Name = "Bob";5Console.WriteLine(a.Name); // "Bob" - a was changed too!
Null References
Reference types can be null:
csharp1Person p = null; // No object23if (p != null)4{5 p.Introduce();6}78// Or use null-conditional9p?.Introduce(); // Only calls if p is not null
Practical Example
csharp1class Rectangle2{3 public double Width;4 public double Height;56 public double GetArea()7 {8 return Width * Height;9 }1011 public double GetPerimeter()12 {13 return 2 * (Width + Height);14 }1516 public void Display()17 {18 Console.WriteLine($"Rectangle: {Width} x {Height}");19 Console.WriteLine($"Area: {GetArea()}");20 Console.WriteLine($"Perimeter: {GetPerimeter()}");21 }22}2324// Usage25Rectangle rect1 = new Rectangle { Width = 5, Height = 3 };26rect1.Display();2728Rectangle rect2 = new Rectangle { Width = 10, Height = 7 };29rect2.Display();
Summary
In this lesson, you learned:
- A class is a blueprint that defines data and behavior
- An object is an instance of a class
- Use
newto create objects - Classes organize code and model real-world entities
- Classes are reference types (variables hold references, not values)
- Object initializer syntax provides a concise way to set properties
Next, we'll explore fields and properties in more detail.