Skip to content

Intermediate · Classes and objects · topic 14 of 43 · 30 min

Classes, objects and constructors

Explanation

A class is a blueprint that describes what something has (data, in fields) and what it can do (methods). An object is one real thing made from that blueprint with new. A constructor is a special method that runs when the object is created and sets it up. Each object keeps its own copy of the data.

Why classes?

So far you have stored data in separate variables: name, balance, accountNo. In a real bank there are millions of accounts, and each one has the same kinds of data and the same actions (deposit, withdraw). A class groups the data and the actions together under one name. This style is called object-oriented programming (OOP).

Think of it like this: A class is like the architect's plan for a flat in a housing society. The plan says every flat has a number, an owner and a number of rooms. The flats themselves are objects: flat 101 and flat 102 follow the same plan but have different owners. Building a flat from the plan is like calling new.

Your first class

csharp
class BankAccount
{
    // fields: the data each object holds
    public string Owner = "";
    public decimal Balance;

    // a method: something the object can do
    public void Deposit(decimal amount)
    {
        Balance += amount;
    }
}
Fields are variables that belong to an object. Methods inside a class work on that object's fields. public means code outside the class can use it (next topics explain).

Creating objects with new

csharp
var asha = new BankAccount();
asha.Owner = "Asha";
asha.Deposit(5000m);

var ravi = new BankAccount();
ravi.Owner = "Ravi";
ravi.Deposit(800m);

Console.WriteLine($"{asha.Owner}: {asha.Balance}");   // Asha: 5000
Console.WriteLine($"{ravi.Owner}: {ravi.Balance}");   // Ravi: 800
new creates an object, also called an instance. Each instance has its own Owner and Balance. Use a dot to reach its members.
Tip: In a Program.cs with top-level statements, class declarations must come AFTER the statements, at the bottom of the file. In real projects, put each class in its own file named after it, such as BankAccount.cs.

Constructors

A constructor is a special method with the same name as the class and no return type. It runs automatically when you call new, and its job is to put the object into a valid starting state. If you write no constructor, C# gives you an empty one.

csharp
var acc = new BankAccount("Meena", 1000m);
Console.WriteLine(acc.Balance);   // 1000

class BankAccount
{
    public string Owner;
    public decimal Balance;

    public BankAccount(string owner, decimal openingBalance)
    {
        Owner = owner;
        Balance = openingBalance;
    }
}
Now nobody can create an account without an owner.

The this keyword

csharp
class Student
{
    public string name;
    public int rollNo;

    public Student(string name, int rollNo)
    {
        this.name = name;      // this.name = the field; name = the parameter
        this.rollNo = rollNo;
    }
}
this means "the current object". It is needed when a parameter has the same name as a field.

Several constructors

csharp
class Product
{
    public string Name;
    public decimal Price;

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }

    public Product(string name) : this(name, 0m) { }   // calls the other constructor
}
Constructors can be overloaded like methods. : this(...) reuses another constructor so the setup code is not repeated.

Objects are references

A class is a reference type. The variable holds a reference (an address) to the object, not the object itself. Assigning one variable to another copies the reference, so both names point to the same object.

csharp
var a = new BankAccount("Asha", 100m);
var b = a;            // same object
b.Balance = 999m;
Console.WriteLine(a.Balance);   // 999
This is the same behaviour you saw with arrays.

Object initializers and ToString

csharp
var c = new City { Name = "Bhopal", Pin = 462001 };
Console.WriteLine(c);    // Bhopal - 462001

class City
{
    public string Name = "";
    public int Pin;
    public override string ToString() => $"{Name} - {Pin}";
}
An object initializer { ... } sets members right after construction. Overriding ToString controls what printing an object shows; without it you would see just the class name.

Since C# 12 you may also see primary constructors on classes: class Product(string name, decimal price) { ... }. The parameters can be used anywhere in the class body. They are handy for short classes; the classic constructor shown above works everywhere and is what most code uses.

Common mistakes and fixes

  • Declaring a variable but never calling new: BankAccount acc; acc.Deposit(5) does not compile (unassigned), and a field left null throws NullReferenceException.
  • Calling an instance method from static code without an object: error CS0120, an object reference is required. Create an object first, or make the method static if it uses no object data.
  • Giving a constructor a return type (public void BankAccount()): that makes an ordinary method, not a constructor.
  • Forgetting this. when names clash: name = name; assigns the parameter to itself and the field stays empty. The compiler warns you; use this.name = name.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Classes, objects and constructors · 1/7

Classes and objects

In this lesson you will create your own types with classes.

Prefer a video by a teacher? Find free videos on “C# classes objects constructors tutorial for beginners OOP” on YouTube ↗

In real life: A Flipkart-style shopping cart item

An e-commerce app models each cart line as an object: which product, its price and the quantity. The object knows how to work out its own line total, so the cart page, the checkout page and the invoice all use the same logic.

csharp
var line1 = new CartItem("Cotton kurta", 799m, 2);
var line2 = new CartItem("Steel bottle", 349m, 1);

Console.WriteLine(line1);
Console.WriteLine(line2);
Console.WriteLine($"Cart total: {line1.LineTotal() + line2.LineTotal()}");

class CartItem
{
    public string Product;
    public decimal Price;
    public int Quantity;

    public CartItem(string product, decimal price, int quantity)
    {
        Product = product;
        Price = price;
        Quantity = quantity;
    }

    public decimal LineTotal() => Price * Quantity;
    public override string ToString() => $"{Product} x{Quantity} = {LineTotal()}";
}
Shows Cotton kurta x2 = 1598, Steel bottle x1 = 349, Cart total: 1947.

Practice (0/4 done)

Task 1 · Question

Which line creates an object of class Car?

Task 2 · Question

What does this print? var a = new Counter(); var b = a; b.Count = 5; Console.WriteLine(a.Count); class Counter { public int Count; }

Task 3 · Question

What is special about a constructor?

Task 4 · Practice

Create a class Student with fields Name, RollNo and an int[] Marks. Add a constructor that sets all three, a method Average() that returns a double, and override ToString to show "RollNo Name: average". Create two students and print them.

Quick quiz

Question 1

1.What is the relationship between a class and an object?

Question 2

2.What does this refer to inside a method?

Question 3

3.In Program.cs with top-level statements, where must class declarations go?

Question 4

4.What does : this(name, 0m) after a constructor header do?

Question 5

5.Without overriding ToString, what does printing an object of class City show?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is the relationship between a class and an object?

Answer: A class is a blueprint; an object is an instance made from it

You define a class once and create many objects from it.

What does this refer to inside a method?

Answer: The current object

this is the object the method was called on.

In Program.cs with top-level statements, where must class declarations go?

Answer: After the statements

Type declarations must follow the top-level statements (or live in other files).

What does : this(name, 0m) after a constructor header do?

Answer: Calls another constructor of the same class first

It chains to another constructor to reuse its setup code.

Without overriding ToString, what does printing an object of class City show?

Answer: Its class name (like City)

The default ToString returns the type's full name.

Two objects of the same class…Related

Answer: Each have their own copies of instance fields

Instance fields belong to each object.

From Classes and objects

Why do Flutter widgets often use const constructors?Related

Answer: Constant widgets are created once and can be skipped during rebuilds

const saves work at run time.

From Classes and constructors

What is the return type of a constructor?Related

Answer: It has none

Constructors have no return type, not even void.

From Constructors and this

What is the difference between a class and an object?Related

Answer: A class is the blueprint; an object is one thing made from it

One class can make many objects, each with its own data.

From Classes and objects

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Classes and objects” before its exam: Properties: get, set, init and required, Access modifiers, static members and encapsulation, Structs, value types and reference types.
  2. Module 4 exam: Classes and objects · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Inheritance, interfaces and records. 43 topics left in the course before the final exam.

← Previous: null, nullable types and null-safe operators