What if a simple number in your program could silently cause big bugs? Properties help you stop that!
Properties vs fields in C Sharp (C#) - When to Use Which
Imagine you have a class representing a person, and you store their age as a simple number. You directly access and change this number everywhere in your code.
Directly changing the age number everywhere can cause mistakes, like setting an impossible age (negative or too high). It's hard to check or control these changes, and bugs sneak in easily.
Properties let you control how values like age are accessed and changed. You can add checks or extra actions automatically, keeping your data safe and your code clean.
public int age; // direct field access
person.age = -5; // no check, wrong valueprivate int age;
public int Age {
get => age;
set {
if (value >= 0) age = value;
}
}
person.Age = -5; // ignored, safeProperties enable safe, controlled access to data, making your programs more reliable and easier to maintain.
In a banking app, you store account balance. Using properties, you prevent setting a negative balance directly, protecting users from errors.
Fields store data directly but offer no control.
Properties let you add rules when getting or setting data.
This control helps prevent bugs and keeps data valid.