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 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.
C# code does not run on this page. Run your edited code on your own computer with dotnet run.
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 = newWallet();acc.Balance = -999m;Console.WriteLine(acc.Balance);classWallet{publicdecimalBalance { get; set; }}
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.
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.
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 = newTag();tag.Name = "sale";classTag{publicstringName {get => Name;set => Name = value.Trim(); }}
When you run itStack overflow.
Fixed
var tag = newTag();tag.Name = " sale ";Console.WriteLine(tag.Name);classTag{privatestring name = "";publicstringName {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 = newAccount { 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.