12 minlesson

Classes and Objects

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)
csharp
1// A class definition - the blueprint
2class Dog
3{
4 public string Name;
5 public int Age;
6
7 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.

csharp
1// Creating objects from the Dog class
2Dog myDog = new Dog();
3myDog.Name = "Buddy";
4myDog.Age = 3;
5myDog.Bark(); // Output: Buddy says: Woof!
6
7Dog 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:

csharp
1// Creating an object
2ClassName objectName = new ClassName();
3
4// Examples
5Dog pet = new Dog();
6Car myCar = new Car();
7Person user = new Person();

Class Definition Syntax

csharp
1class ClassName
2{
3 // Fields (data)
4 public int field1;
5 public string field2;
6
7 // Properties (covered next lesson)
8 public int Property { get; set; }
9
10 // Methods (behavior)
11 public void DoSomething()
12 {
13 // Method body
14 }
15}

A Complete Example

csharp
1// Define the class
2class Person
3{
4 public string FirstName;
5 public string LastName;
6 public int Age;
7
8 public void Introduce()
9 {
10 Console.WriteLine($"Hi, I'm {FirstName} {LastName}, age {Age}.");
11 }
12
13 public void HaveBirthday()
14 {
15 Age++;
16 Console.WriteLine($"Happy birthday! {FirstName} is now {Age}.");
17 }
18}
19
20// Use the class
21Person person1 = new Person();
22person1.FirstName = "Alice";
23person1.LastName = "Smith";
24person1.Age = 25;
25
26Person person2 = new Person();
27person2.FirstName = "Bob";
28person2.LastName = "Jones";
29person2.Age = 30;
30
31person1.Introduce(); // Hi, I'm Alice Smith, age 25.
32person2.Introduce(); // Hi, I'm Bob Jones, age 30.
33
34person1.HaveBirthday(); // Happy birthday! Alice is now 26.

Why Use Classes?

1. Organization

Group related data and behavior together.

csharp
1// Without classes - loose variables
2string playerName = "Hero";
3int playerHealth = 100;
4int playerScore = 0;
5
6// With a class - organized
7class Player
8{
9 public string Name;
10 public int Health;
11 public int Score;
12}

2. Reusability

Create multiple objects from one class.

csharp
1Player 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.

csharp
1class BankAccount
2{
3 private decimal balance; // Hidden from outside
4
5 public void Deposit(decimal amount)
6 {
7 if (amount > 0)
8 balance += amount;
9 }
10
11 public decimal GetBalance() => balance;
12}

4. Modeling Real-World Entities

Represent things from the problem domain.

csharp
1class Book
2{
3 public string Title;
4 public string Author;
5 public int Pages;
6}
7
8class Car
9{
10 public string Make;
11 public string Model;
12 public int Year;
13}

Object Initialization Syntax

Traditional Way

csharp
1Person p = new Person();
2p.FirstName = "Alice";
3p.LastName = "Smith";
4p.Age = 25;

Object Initializer Syntax

csharp
1Person p = new Person
2{
3 FirstName = "Alice",
4 LastName = "Smith",
5 Age = 25
6};

Target-Typed new (C# 9+)

csharp
1Person p = new()
2{
3 FirstName = "Alice",
4 LastName = "Smith",
5 Age = 25
6};

Classes in Separate Files

For larger projects, put each class in its own file:

Person.cs

csharp
1public class Person
2{
3 public string Name;
4 public int Age;
5}

Program.cs

csharp
1Person p = new Person();
2p.Name = "Alice";

Reference Types

Classes are reference types. Variables hold a reference to the object, not the object itself.

csharp
1Person a = new Person { Name = "Alice" };
2Person b = a; // b points to the SAME object as a
3
4b.Name = "Bob";
5Console.WriteLine(a.Name); // "Bob" - a was changed too!

Null References

Reference types can be null:

csharp
1Person p = null; // No object
2
3if (p != null)
4{
5 p.Introduce();
6}
7
8// Or use null-conditional
9p?.Introduce(); // Only calls if p is not null

Practical Example

csharp
1class Rectangle
2{
3 public double Width;
4 public double Height;
5
6 public double GetArea()
7 {
8 return Width * Height;
9 }
10
11 public double GetPerimeter()
12 {
13 return 2 * (Width + Height);
14 }
15
16 public void Display()
17 {
18 Console.WriteLine($"Rectangle: {Width} x {Height}");
19 Console.WriteLine($"Area: {GetArea()}");
20 Console.WriteLine($"Perimeter: {GetPerimeter()}");
21 }
22}
23
24// Usage
25Rectangle rect1 = new Rectangle { Width = 5, Height = 3 };
26rect1.Display();
27
28Rectangle 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 new to 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.

Classes and Objects - Anko Academy