C# · Course navigation

C# Classes and Properties

Protect state with a property that only the class can change.

On this page
Before you start

C# methods.

  • Protect state with a property that only the class can change.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A class bundles data and the methods that work on it. A property such as Value looks like a field to callers but is really a pair of accessors. Declaring set as private means outside code can read Value but cannot assign it.

That is encapsulation: the only way to change Value is through Increment, so the class controls its own rules. new Counter() creates an object whose Value starts at the default of 0.

Code example

C#
using System;

class Counter {
  public int Value { get; private set; }

  public void Increment() {
    Value++;
  }
}

class Program {
  static void Main() {
    var counter = new Counter();
    counter.Increment();
    counter.Increment();
    Console.WriteLine(counter.Value);
  }
}
Output
2

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1using System;
2
3class Counter {
4 public int Value { get; private set; }
5
6 public void Increment() {
7 Value++;
8 }
9}
10
11class Program {
12 static void Main() {
13 var counter = new Counter();
14 counter.Increment();
15 counter.Increment();
16 Console.WriteLine(counter.Value);
17 }
18}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Anyone can read Value, but only Counter can set it.—
—
Create an object; Value starts at 0.Value = 0
—
The first call raises Value to 1.Value = 1
—
The second call raises it to 2.Value = 2
—
Read the property and print it.Value = 2
2

Behind the scenes

How C# processes this code

C# compiles to code for the .NET runtime, which invokes the program entry point.

Cost and common mistakes

Each Increment is O(1).

  • Writing counter.Value = 5; outside the class is a compile error because the setter is private.
  • Value-type fields start at their default (0, false), but reference types start as null.

Try it yourself

Add a Reset method that sets Value back to 0.

Reveal answer and reasoning

public void Reset() { Value = 0; } is allowed because it is inside the class.

Further reading