Skip to content
dreamcode
dreamcode
Map
Properties
Lesson 9 of 21
+15 XP on finish
C# OOPChapter 3 · C# Object Oriented Programming

Encapsulating with properties

Properties combine a private field with accessors called get and set. This protects class data by controlling how values are read or written.

Worked example
class SkyItem {
    private int _density;
    public int Density {
        get { return _density; }
        set {
            if (value >= 0) _density = value;
        }
    }
}

How it reads

  • private int _density hides the internal value
  • get { return _density; } runs when reading the property
  • set { ... } runs when writing, with value representing incoming data
Cloud tip: Use auto-implemented properties like public string Name { get; set; } when no validation logic is needed.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. What represents the incoming data in a property set accessor?
  2. 2. What is an auto-implemented property?
Answer every question to unlock the next lesson.