Classes and objects
Classes and objects
A class is a blueprint, an object is a concrete instance of it in memory. A class describes data (fields and properties) and behaviour (methods).
class Student
{
public string Name { get; set; }
public int Grade { get; private set; }
public Student(string name)
{
Name = name;
Grade = 2;
}
public void Improve(int points)
{
Grade = Math.Min(6, Grade + points);
}
public override string ToString() => $"{Name}: {Grade}";
}
Using it
var s = new Student("Ana");
s.Improve(3);
Console.WriteLine(s); // Ana: 5
Key ideas
- Constructor — a method named like the class; runs on
new. - Property (
{ get; set; }) — controlled access to data. - Access modifier —
publicis visible everywhere,privateonly inside the class. This keeps internal state valid (encapsulation). - Reference type — the variable holds a reference; two variables can point to the same object.
The most common mistakes
- Forgetting
new— you get aNullReferenceExceptionon first use. - Public fields instead of properties — anyone can set an invalid value.
Practice
Add an IsExcellent() method to Student that returns true for a grade of 5 or higher.