C-Sharp C#
Properties (Getters & Setters)
ClassesProperties are how C# lets us safely access and change the data inside a class. They control how data is read and updated, while keeping the actual fields protected.
So far our fields have been public, which means anything can change them to anything, including nonsense like a negative age. From now on, our fields will be private, meaning they cannot be touched directly from outside the class. Instead we expose them through properties. This is part of a principle called encapsulation: keeping your data safe and only allowing changes that make sense.
If you've used other languages, you may have written
getName()andsetName()methods. C# has a cleaner, built-in feature for this called properties, and that's what we use instead.
Properties - A
Here's a Person class with a private field name and a public property Name that controls access to it.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 4 more lessons in C-Sharp C#.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.