C# · Object-Oriented Programming

Classes and Objects

A class describes a kind of thing — a Student, an Order, a Product. An object is one real instance of it, with its own data. This is how C# programs model the world.

Beginner 6 min Lesson 11 of 26Examples target C# 13 on .NET 9 unless stated otherwise.
Before you start:Methods
0/26 in C#
On this page · 6 min · Beginner

In simple words#

A class is the blueprint of a house; objects are the actual houses built from it. Every house has the same plan but its own colour and owner.

Class
A blueprint that defines data and behaviour.
Object
A real instance made with new.
Property
A piece of data an object holds.

Learning objectives#

  • Write a class with properties, a constructor and methods
  • Create objects with new
  • Understand that each object has its own data
  • Use object initializers

Explanation#

A class groups data (properties and fields) with behaviour (methods). public members can be used from outside; private members only inside the class.

An auto-property such as public string Name { get; set; } stores a value with no extra code. { get; } makes it read-only after the constructor.

The constructor has the same name as the class and no return type. It runs when you write new Student(...) and sets up a valid starting state.

Each object created with new has its own copy of the data. Changing one student’s marks never affects another student.

Object initializers set properties right after creation: new Product { Name = "Pen", Price = 10m }.

In a top-level program, classes are declared after the statements at the top of the file. In real projects each class usually lives in its own file.

Syntax#

C# Illustrative
public class Student
{
    public string Name { get; }        // read-only property
    public int Year { get; set; }      // read-write property


    public Student(string name, int year)   // constructor
    {
        Name = name;
        Year = year;
    }


    public string Describe() => 
quot;
{Name}, year {Year}";
} var s = new Student("Asha", 2);

Code example: Students with their own marks#

C#Program.cs Illustrative
var asha = new Student("Asha", 2);
var ravi = new Student("Ravi", 1);


asha.AddMark(91);
asha.AddMark(85);
ravi.AddMark(70);


Console.WriteLine(asha.Describe());
Console.WriteLine(ravi.Describe());


ravi.Year = 2;   // settable property
Console.WriteLine(ravi.Describe());


class Student
{
    private readonly List<int> _marks = new();


    public string Name { get; }
    public int Year { get; set; }


    public Student(string name, int year)
    {
        Name = name;
        Year = year;
    }


    public void AddMark(int mark) => _marks.Add(mark);


    public double Average() => _marks.Count == 0 ? 0 : _marks.Average();


    public string Describe() => 
quot;
{Name} (year {Year}) average {Average():F1}";
}
Expected output
Asha (year 2) average 88.0
Ravi (year 1) average 70.0
Ravi (year 2) average 70.0

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. new Student("Asha", 2) runs the constructor, which fills Name and Year.
  2. _marks is a private field: outside code cannot touch the list directly.
  3. AddMark is the only way to add marks; each student has a separate list.
  4. Average uses LINQ’s Average and guards against an empty list.
  5. Year has a setter, so it can change later; Name has only get, so it cannot.

Real-world use case#

In an ASP.NET Core app, classes model the domain (Order, Customer, Product), the requests (CreateOrderRequest) and the services that do the work (OrderService). Everything starts with classes.

Common mistakes#

Making every field public

Public fields let any code put an object into an invalid state. Use properties and keep fields private.

Constructor with a return type

public void Student(...) is a normal method, not a constructor, so it never runs on new. Constructors have no return type.

NullReferenceException on an unset property

If a List property is never created, Add crashes. Initialise collections where you declare them.

Best practices#

  • One class per file, named after the class
  • Use PascalCase for classes, properties and methods; _camelCase for private fields
  • Make properties read-only unless they really need to change
  • Initialise collections at declaration

Remember this#

Class = blueprint. Object = one thing built from it.

Constructor: same name as the class, no return type.

{ get; } = read-only. { get; set; } = read-write.

Practice exercise#

Your task: Create a Product class with Name and Price properties, a constructor, and a method PriceWithGst() that returns the price plus 18%. Create two products and print both prices with GST.

Need a hint?
Use decimal for Price and multiply by 1.18m.
Show solution
C# Illustrative
var pen = new Product("Pen", 20m);
var bag = new Product("Bag", 500m);
Console.WriteLine(
quot;
{pen.Name}: {pen.PriceWithGst():F2}"); // Pen: 23.60
Console.WriteLine(
quot;
{bag.Name}: {bag.PriceWithGst():F2}"); // Bag: 590.00
class Product { public string Name { get; } public decimal Price { get; } public Product(string name, decimal price) { Name = name; Price = price; } public decimal PriceWithGst() => Price * 1.18m; }

Mini quiz#

Classes and Objects quizMultiple choice Question 1 of 3

Which statement about constructors is true?

Score so far: 0/0

Want more? Practise all C# MCQs · C# interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.