Tools
Log in
English

Learn to codeC#

C# encapsulation

Based on C# 12required · C# 11+init · C# 9+

C# properties with private set, init and required, shown on a bank account.

In one line

Hide the values inside an object and open only a few properties and methods, each with checks, as the way to change them. In C#, giving get and set different access levels on a property says this in one line.

Why you need it

If Balance is a public field, as below, nothing stops the balance from dropping to -200,000. In a larger program the lines that change it spread over dozens of places, and tracking down the one that broke it takes a long time.

Change Balance to { get; private set; } and reading still works while writing moves inside the class. When a rule changes, you look at Deposit and Withdraw and nothing else.

Everyday picture

Think of a post office box. Anyone can see through the little window whether there is mail (get), but only the renter has the key (private set). Who the renter is gets decided once, when the box is first rented (init).

The bug you get with public fields

var acc = new Account();acc.Owner = "Jisoo";acc.Balance = 300_000m;acc.Balance -= 500_000m;acc.Nickname = "";Console.WriteLine($"[{acc.Nickname}] {acc.Owner}: {acc.Balance:N0} won"); class Account{    public string Owner = "";    public string Nickname = "main";    public decimal Balance;}

When you run it

[] Jisoo: -200,000 won

The balance and the nickname are public fields, so any code can change them. Taking 500,000 out of an account that holds 300,000 is not stopped, and the balance ends at -200,000.

An empty nickname goes in as well. When lines like these are scattered around a program, finding the one that broke the balance is hard work.

Example code

Program.cs · 50 lines
var acc = new Account { Owner = "Jisoo" };acc.Nickname = "  travel fund  ";acc.Deposit(300_000m);bool ok = acc.Withdraw(500_000m);acc.Withdraw(120_000m);Console.WriteLine($"{acc.Nickname} ({acc.Owner}): {acc.Balance:N0} won");Console.WriteLine($"Refused: {acc.Refused}, low balance: {acc.IsLow}"); class Account{    private string nickname = "main";     public required string Owner { get; init; }    public decimal Balance { get; private set; }    public int Refused { get; private set; }    public bool IsLow => Balance < 200_000m;     public string Nickname    {        get => nickname;        set        {            if (string.IsNullOrWhiteSpace(value))            {                throw new ArgumentException("Nickname cannot be empty");            }            nickname = value.Trim();        }    }     public void Deposit(decimal amount)    {        if (amount <= 0)        {            throw new ArgumentOutOfRangeException(nameof(amount));        }        Balance += amount;    }     public bool Withdraw(decimal amount)    {        if (amount > Balance)        {            Refused++;            return false;        }        Balance -= amount;        return true;    }}

When to use it

  • Values that must never be wrong (balance, stock, age, nickname length)
  • Changes that must trigger something else (count a refusal, write a log line)
  • Values set once and never again (owner, join date). Use init and required.

A get-only computed property (IsLow => Balance < 200_000m) never needs updating, so it is always right.

Use decimal rather than double for money; it stores values like 0.1 exactly. The m after a number marks it as decimal.

Common mistakes

Leaving set open on an auto-property

{ get; set; } is shorter to type but no safer than a public field: anyone can store -999. Close the setter with private and check inside a method that says why the value changes.

Wrong

var acc = new Wallet();acc.Balance = -999m;Console.WriteLine(acc.Balance); class Wallet{    public decimal Balance { get; set; }}

When you run it-999

Fixed

var acc = new Wallet();acc.Deposit(-999m);Console.WriteLine(acc.Balance); class Wallet{    public decimal Balance { get; private set; }     public void Deposit(decimal amount)    {        if (amount > 0)        {            Balance += amount;        }    }}

When you run it0

Trying to change an init property later

init accepts a value only while the object is being created. If the owner changes, that is a new account: create a new object, or, if the value really must change, replace init with a method that checks it.

Wrong

var acc = new Account { Owner = "Jisoo" };acc.Owner = "Somebody";

What the C# compiler sayserror CS8852: Init-only property or indexer 'Account.Owner' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

Fixed

var acc = new Account { Owner = "Jisoo" };var copy = new Account { Owner = "Somebody" };Console.WriteLine($"{acc.Owner} {copy.Owner}");

When you run itJisoo Somebody

A property that calls itself

Name = ... inside set calls set again, round and round, until the program dies with a stack overflow. Keep the value in a separate private field (lowercase name) and read and write that field.

Wrong

var tag = new Tag();tag.Name = "sale"; class Tag{    public string Name    {        get => Name;        set => Name = value.Trim();    }}

When you run itStack overflow.

Fixed

var tag = new Tag();tag.Name = " sale ";Console.WriteLine(tag.Name); class Tag{    private string name = "";     public string Name    {        get => name;        set => name = value.Trim();    }}

When you run itsale

Check yourself

Question 1

An account holds 50,000. What does calling Withdraw(80_000m) print?

var a = new Account { Owner = "Jun" };a.Deposit(50_000m);Console.WriteLine($"{a.Withdraw(80_000m)} {a.Balance}");

Show the answer

Answer: 2. False 50000 When the amount is more than the balance, only the refusal count goes up and it returns false. The balance stays 50000.

Question 2

What happens if code outside the class writes a.Balance = 0m;?

Show the answer

Answer: 2. It does not compile The set of Balance is private, so nothing outside Account can assign it. The compiler stops it with error CS0272.

Questions people ask

What is the difference between a field and a property?

A field is a slot that holds a value. A property is syntax that lets get and set methods be used like a field. Expose values as properties and keep fields private.

How do I choose between private set and init?

Use private set when the class must change the value during the object’s life, init when it is set once at creation and never again. Add required when callers must always provide it.

Is { get; set; } on its own encapsulation?

No. If anyone can set it, it is no different from a public field. Close the setter or validate inside it to get the benefit.