C# Foundations

Lesson 4 of 6

Methods and Classes

A class bundles data (fields) and behavior (methods) together, it's the blueprint for creating objects.

class Student
{
    public string Name;
    public int Xp;

    public Student(string name, int xp = 0)
    {
        Name = name;
        Xp = xp;
    }

    public int GainXp(int amount)
    {
        Xp += amount;
        return Xp;
    }
}

var ada = new Student("Ada");
ada.GainXp(50);
Console.WriteLine($"{ada.Name} has {ada.Xp} XP");

Key pieces

  • The method with the same name as the class (Student(string name, int xp = 0)) is the constructor, it runs when you create a new instance.
  • new Student("Ada") allocates a new object and runs its constructor.
  • public fields and methods are accessible from outside the class, by convention C# method and property names use PascalCase (GainXp, not gainXp).

📝 Classes Quiz

Passing score: 70%
  1. 1.What is the method that runs automatically when you create a new instance of a class called?

  2. 2.The ____ keyword allocates a new instance of a class and runs its constructor.

  3. 3.By convention, C# method names use PascalCase, like GainXp rather than gainXp.