Tutorials / C# for Beginners / Classes and objects

Classes and objects

14 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. Expense tracker, part 2: the menu and summaries

From loose variables to a model

Imagine you track students. Each student has a name, an age and a list of marks. You could keep three parallel lists, one for names, one for ages, one for marks. It works until you sort one list and forget the others. Then every student has someone else's marks.

A class solves this. It groups the data and the behaviour of one kind of thing into a single unit. A class is the blueprint. An object is one actual thing built from that blueprint. Student is a class. Ayesha, aged 20, with her marks, is an object.

Writing a class

Put a class in its own file when it grows. For small examples you can place it at the bottom of Program.cs. Type declarations must come after top-level statements.

var ayesha = new Student("Ayesha", 20);
ayesha.AddMark(82);
ayesha.AddMark(91);
ayesha.AddMark(77);

var bilal = new Student("Bilal", 22);
bilal.AddMark(65);
bilal.AddMark(70);

Console.WriteLine(ayesha.Describe());
Console.WriteLine(bilal.Describe());

// Two variables, one object
Student same = ayesha;
same.AddMark(100);
Console.WriteLine(ayesha.Marks.Count);   // 4, not 3

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

    public string Name;
    public int Age;

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public IReadOnlyList<int> Marks => _marks;

    public void AddMark(int mark)
    {
        if (mark < 0 || mark > 100)
        {
            return;
        }
        _marks.Add(mark);
    }

    public double Average()
    {
        if (_marks.Count == 0) return 0;
        return _marks.Average();
    }

    public string Describe()
    {
        return $"{Name} ({Age}) has {_marks.Count} marks, average {Average():F1}";
    }
}

Walking through it

The class Student block holds everything about a student. Inside it we see three kinds of member.

  • Fields hold data. Name and Age are public fields. _marks is private, so only code inside Student can touch it. A leading underscore on private fields is a common naming habit.
  • Constructors run when you write new Student(...). Their job is to put the new object into a valid state. A constructor has the class name and no return type.
  • Methods are the actions. AddMark changes the object. Average and Describe report on it.

Why is _marks private? Because I want AddMark to check that a mark is between 0 and 100. If the list were public, anyone could add 5000. Hiding the data and exposing a method to change it is called encapsulation. The class protects its own rules. The public Marks property exposes the list as read-only, so outside code can look but not change it.

The keyword readonly on _marks means the field can be assigned only in the declaration or a constructor. The list itself can still change, because readonly locks the variable, not the contents.

References, not copies

The line Student same = ayesha; does not create another student. It creates a second variable pointing to the same object. When we add a mark through same, ayesha sees it. Classes are reference types. This is a source of many beginner bugs, so run the example and look at the number 4.

Numbers and booleans behave differently. They are value types, and assigning one copies the value.

Access modifiers

public means anyone can use it. private means only this class. If you write neither, class members are private by default. Start private and open up only what other code really needs.

Common mistakes

  • Making every field public. It is faster to type and worse in every other way.
  • Forgetting new. Declaring Student s; creates no object. It is null until you assign one.
  • Thinking assignment copies an object. It copies the reference.
  • Putting the class before the statements in Program.cs. Top-level statements must come first.

Try it yourself

  1. Write a BankAccount class with a private balance, a constructor taking an owner name, and methods Deposit and Withdraw. Withdraw must refuse to go below zero.
  2. Create two accounts and move money from one to the other.
  3. Add a Describe method that returns a line of text with the owner and balance.
csharp
var ayesha = new Student("Ayesha", 20);
ayesha.AddMark(82);
ayesha.AddMark(91);
ayesha.AddMark(77);

var bilal = new Student("Bilal", 22);
bilal.AddMark(65);
bilal.AddMark(70);

Console.WriteLine(ayesha.Describe());
Console.WriteLine(bilal.Describe());

// Two variables, one object
Student same = ayesha;
same.AddMark(100);
Console.WriteLine(ayesha.Marks.Count);   // 4, not 3

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

    public string Name;
    public int Age;

    public Student(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public IReadOnlyList<int> Marks => _marks;

    public void AddMark(int mark)
    {
        if (mark < 0 || mark > 100)
        {
            return;
        }
        _marks.Add(mark);
    }

    public double Average()
    {
        if (_marks.Count == 0) return 0;
        return _marks.Average();
    }

    public string Describe()
    {
        return $"{Name} ({Age}) has {_marks.Count} marks, average {Average():F1}";
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account