Junior — Middle
Can you explain what is meant by invariants in the context of classes?
sobes.tech AI
Answer from AI
Invariants in the context of classes are conditions or properties that must always remain true for an object of the class throughout its lifetime, except during moments when the object's state is being changed.
They help ensure the correctness and integrity of data within the object. For example, if a class has a field "age," an invariant could be the condition that the age must always be non-negative.
In C#, invariants are usually checked in constructors and methods that modify the object's state to prevent violations of these conditions.
Example:
class Person
{
private int age;
public int Age
{
get => age;
set
{
if (value < 0)
throw new ArgumentException("Age cannot be negative");
age = value;
}
}
public Person(int age)
{
Age = age; // invariant is checked here
}
}
Here, the invariant is the condition age >= 0, which is maintained through the check in the setter and constructor.