0
0
C Sharp (C#)programming~3 mins

Properties vs fields in C Sharp (C#) - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if a simple number in your program could silently cause big bugs? Properties help you stop that!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
public int age; // direct field access
person.age = -5; // no check, wrong value
After
private int age;
public int Age {
  get => age;
  set {
    if (value >= 0) age = value;
  }
}
person.Age = -5; // ignored, safe
What It Enables

Properties enable safe, controlled access to data, making your programs more reliable and easier to maintain.

Real Life Example

In a banking app, you store account balance. Using properties, you prevent setting a negative balance directly, protecting users from errors.

Key Takeaways

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.