C# ยท Chapter 29 of 46

C# OOP: Classes & Objects

Object-Oriented Programming (OOP) organizes code around objects, which are instances of classes. A class is a blueprint that defines fields (data) and methods (behavior), and an object is a specific instance created from that class.

C# is a fully object-oriented language, and understanding classes and objects is essential for writing well-structured, real-world C# applications.

Syntax
class ClassName {
  // fields
  // methods
}
ClassName obj = new ClassName();

Defining a class

A class is defined with the `class` keyword, containing fields to store data and methods to define behavior. For example, a Car class might have fields for color and model.

Creating objects

An object is created from a class using the `new` keyword, like `Car myCar = new Car();`. Each object has its own copy of the class's fields.

Example 1 (csharp)
using System;

class Car {
  public string color = "Red";
}

class Program {
  static void Main() {
    Car myCar = new Car();
    Console.WriteLine(myCar.color);
  }
}
Output
Red

myCar is an object created from the Car class, and it has access to the color field.

Example 2 (csharp)
using System;

class Car {
  public string model = "Sedan";
  public void Honk() {
    Console.WriteLine("Beep!");
  }
}

class Program {
  static void Main() {
    Car myCar = new Car();
    myCar.Honk();
  }
}
Output
Beep!

Honk() is a method defined in the Car class, called on the myCar object.

Key points

  • A class is a blueprint; an object is an instance of that class.
  • Fields store data, and methods define behavior on a class.
  • The `new` keyword creates a new object from a class.
  • Multiple objects created from the same class have independent field values.
๐Ÿ’ก Note: Class names in C# conventionally use PascalCase, like Car or CustomerAccount.

๐Ÿ“ Quick Quiz

1. What is a class?

2. Which keyword creates an object from a class?

3. Do two objects from the same class share the same field values?