C# Classes and Properties
Protect state with a property that only the class can change.
On this page
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
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);
}
}2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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); }}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
| Step / line | What happens | State after step | Output 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.