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.publicfields and methods are accessible from outside the class, by convention C# method and property names use PascalCase (GainXp, notgainXp).