Access modifiers
“What are access modifiers, and why make a property's setter private?”
Words in front of a class member that say who may use it. They let a class hide its data and open one checked door.
See it
1/8Before. is with a public setter: any code anywhere can read it and write it.
In plain words
An access modifier is a word like or in front of a field, property or method. It says which code may use it. The compiler (the tool that turns your code into a program when you build) checks it: break the rule and the build fails. Make the data hard to reach () and give outside code one method that checks before it changes anything.
- Access modifiers control visibility: is visible everywhere, only inside the class, inside the class and classes that inherit from it, inside the same assembly.
- Class members are by default; a top-level class is by default.
- I expose state as
{ get; private set; }and change it only through methods like that validate first. That is encapsulation: the class protects its own invariants, the rules that must always hold, like a balance never going below 0. - It is a compile-time rule, not security: reflection (code that inspects classes while the app runs) can still read private members.
In the lending API
The same class before and after, plus the report code that broke it. Press Next line to walk through them.
What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
What is the default if you write no modifier?
Inside a class, members are . A class written straight in a namespace (top-level) is . Teams still write out loud, so the reader does not have to remember.
What does really mean?
Visible only inside the same assembly: the one .dll a project builds. A helper class in the Lending.Domain project marked cannot be used from the API project. Useful for code you do not want other teams to depend on.
Why not…Why not keep a public setter and put the check inside it?
That works for one rule, but
loan.Balance = 800hides what happened.ApplyPayment(200)names the business action, can check against the old balance, and can later record the payment too. The setter would let any code jump the balance to any number that passes the check.Is a security feature?
No. It is a rule the compiler checks for normal code. (code that inspects classes while the app runs) can still read and write private members. It protects against mistakes, not attackers.
Where does matter?
When one class is built on another: a child class can use its parent's members, outside code cannot. See .
private protectedandprotected internalare rare combinations; know they exist.
Traps
- Don't say
Private means the value is hidden from everyone at run time.SayIt is a compile-time rule. Reflection can still reach it. - Don't say
Make every property with get and set, it's easier.SayExpose , keep , and change state through methods that check.