.NET Academy

Classes and objects

Bundle data and behavior together by defining your own types with classes.

12 min read

You will learn

  • Define a class with fields and methods
  • Write a constructor and create objects with new
  • Explain the difference between a class and an object
  • Use this to refer to the current object

From loose variables to objects

Imagine a program that manages books. With what you know so far, each book is a pile of separate variables:

string title1 = "Dune";      string author1 = "Frank Herbert";  int pages1 = 412;
string title2 = "Neuromancer"; string author2 = "William Gibson"; int pages2 = 271;

Nothing ties title1 to pages1, and every method needs three parameters per book. Classes fix this: they let you define your own type that bundles data (fields) and behavior (methods) together.

Defining a class

class Book
{
    // Fields: the data each Book carries
    private string title;
    private string author;
    private int pages;
 
    // Constructor: runs when a Book is created
    public Book(string title, string author, int pages)
    {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
 
    // Methods: what a Book can do
    public bool IsLong() => pages > 400;
 
    public string Describe() => $"{title} by {author} ({pages} pages)";
}

Creating objects

A class is a blueprint. To get an actual book, create an object (an instance) with new:

var dune = new Book("Dune", "Frank Herbert", 412);
var neuromancer = new Book("Neuromancer", "William Gibson", 271);
 
Console.WriteLine(dune.Describe());       // Dune by Frank Herbert (412 pages)
Console.WriteLine(neuromancer.IsLong());  // False

Each object has its own copy of the fields. Calling dune.IsLong() looks at Dune's pages; neuromancer.IsLong() looks at Neuromancer's.

Where do classes go?

In a program with top-level statements, type declarations like class Book go after the top-level code, at the bottom of the file. In larger projects, each class usually lives in its own file, like Book.cs.

Constructors

A constructor has the same name as the class and no return type. Its job is to put a new object in a valid starting state.

public Book(string title, string author, int pages)
{
    this.title = title;
    ...
}

The keyword this means "the object being constructed (or the object a method was called on)". Here it distinguishes the field this.title from the parameter title.

A class can have several constructors (overloads), and if you write none, C# provides an empty one for you.

Access modifiers: public and private

ModifierWho can use it
publicAny code
privateOnly code inside this class (the default for members)

Making fields private and methods public is a core idea called encapsulation: the object controls its own data. Outside code can ask a Book to describe itself, but can't set its page count to -5.

dune.pages = -5;   // ❌ compile error: 'Book.pages' is inaccessible due to its protection level

The next lesson introduces properties — the idiomatic way to expose data safely.

Objects are references

A variable of a class type doesn't contain the object itself; it holds a reference to it. Copying the variable copies the reference — both variables then point to the same object:

var a = new Book("Dune", "Frank Herbert", 412);
var b = a;          // b points to the same Book as a

You'll explore what that means in depth in Value vs reference types (Track 3).

Try it

Program.cs
Loading editor…

C# runtime not loaded

Key takeaways

  • A class is a blueprint defining fields (data) and methods (behavior).
  • An object is an instance created with new; each has its own field values.
  • Constructors initialize new objects; this refers to the current object.
  • Keep fields private and expose behavior through public members — that's encapsulation.

Exercise

Complete the Rectangle class. The constructor stores the width and height; Area returns width × height, Perimeter returns 2 × (width + height), and IsSquare returns true when both sides are equal.

Program.cs
Loading editor…

C# runtime not loaded

Hint 1

The parameters have the same names as the fields, so use this to tell them apart: this.width = width;

Hint 2

Methods can read the object's fields directly — Area() can just return width * height.

Show solution
var r = new Rectangle(3, 4);
Console.WriteLine($"Area: {r.Area()}, perimeter: {r.Perimeter()}");

class Rectangle
{
    private double width;
    private double height;

    public Rectangle(double width, double height)
    {
        this.width = width;
        this.height = height;
    }

    public double Area() => width * height;

    public double Perimeter() => 2 * (width + height);

    public bool IsSquare() => width == height;
}

Quiz

4 questions · 3 correct to pass
  1. 1.What's the relationship between a class and an object?

  2. 2.What is a constructor?

  3. 3.Why mark fields as private?

  4. 4.Inside a method, what does `this` refer to?

To complete this lesson

  • ○ Solve the exercise
  • ○ Pass the quiz (3/4 correct)