Intermediate · Classes and objects · topic 14 of 43 · 30 min
Classes, objects and constructors
Explanation
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).
Your first class
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;
}
}Creating objects with new
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: 800Constructors
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.
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;
}
}The this keyword
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;
}
}Several constructors
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
}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.
var a = new BankAccount("Asha", 100m);
var b = a; // same object
b.Balance = 999m;
Console.WriteLine(a.Balance); // 999Object initializers and ToString
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}";
}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
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.
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()}";
}Practice (0/4 done)
Which line creates an object of class Car?
What does this print? var a = new Counter(); var b = a; b.Count = 5; Console.WriteLine(a.Count); class Counter { public int Count; }
What is special about a constructor?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Properties: get, set, init and requiredClasses and objects · same module
- Access modifiers, static members and encapsulationClasses and objects · same module
- Structs, value types and reference typesClasses and objects · same module
- Classes and objectsJava Programming (Core to Spring Boot) · Classes and objects
- Classes and constructorsFlutter and Dart · Null safety and object-oriented Dart
- Constructors and thisJava Programming (Core to Spring Boot) · Classes and objects
Questions people ask about this
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.
What is the return type of a constructor?Related
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
- 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.
- Module 4 exam: Classes and objects · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Inheritance, interfaces and records. 43 topics left in the course before the final exam.