Module 1 · The Four Pillars in C# · Lesson 2 of 13
Encapsulation and Access Modifiers in C#: Keep Objects Valid
What this lesson teaches
C# access modifiers control which code can use a type or member. Learn their defaults and how encapsulation keeps objects valid.
In the booking counter below, encapsulation keeps the count between zero and two. Its state—the values it stores—changes only through members that check those rules. Making everything private is not enough if a public method still accepts invalid changes.
After this lesson, you can explain:
- The six accessibility levels, the separate
filemodifier, and the defaults. - Why
protected internalmeans OR, whileprivate protectedmeans AND. - How properties and checked methods protect an object's state.
- Why returning a list as read-only may still let callers change it.
For the basics, see Protect Object State with Constructors and Methods and Properties, Init, and Immutability Boundaries.
C# access modifiers and their defaults
An assembly is a .dll or .exe produced by compiling C# files together in a single compilation. See Microsoft's assembly definition. Access rules often depend on whether the calling code belongs to that same assembly, not whether it uses the same namespace.
C# has six accessibility levels:
| Modifier | Which code can access it? |
|---|---|
public | Code anywhere, provided the containing type is accessible. |
private | Code within the containing class or struct. |
protected | Code within the containing class or a derived class, subject to the receiver rule explained below. |
internal | Code in the same assembly. |
protected internal | Code in the same assembly OR code in a derived class elsewhere. |
private protected | Code in the containing class, or a derived class in the same assembly. Derivation AND the same assembly are required for derived-class access. |
By default, another assembly cannot access internal members. To let a test project access them, put the InternalsVisibleTo attribute on the assembly under test and name the test assembly. This creates a friend assembly: the named assembly can access internal members, not just the ones used by a particular test.
Structs cannot declare their own base class. They cannot have protected, protected internal, or private protected members. Declaring a protected member in a struct produces CS0666.
Interface members are public by default. Since C# 8, you may write another access modifier on an interface member, for example a private helper used by a default method. A default method supplies its implementation inside the interface.
A top-level type is declared outside any other type. A nested type is declared inside another type.
| Declaration without an access modifier | Default |
|---|---|
| Top-level class, struct, interface, or enum | internal |
| Class or struct member, including a nested type | private |
| Interface member | public |
| Enum member | Always public; you cannot give it an access modifier. |
The separate file modifier restricts a top-level type to its source file. The file keyword reference describes this separate modifier. You cannot combine it with an access modifier. For example, file class ParserHelper declares a helper visible only within that file.
A public member does not make its containing type public. An internal class with a public constructor is still internal.
The mistake to avoid. Do not say that everything defaults to private. Top-level interfaces default to internal, while interface members default to public.
In an interview, say: “C# has public, private, protected, internal, protected internal, and private protected accessibility. There is also file for file-local top-level types. Top-level types default to internal, class and struct members to private, and interface members to public. Enum members are always public.”
Let the object check every change
Suppose a booking counter must stay between zero and two. A public field would let callers assign any number.
Instead, we expose a property callers can read and methods that control changes. In this program, callers read Count, while Reserve() and Release() change it inside BookingCounter.
Before running this program, predict the count after the third reservation attempt.
var counter = new BookingCounter();
counter.Reserve();
counter.Reserve();
try
{
counter.Reserve();
}
catch (InvalidOperationException)
{
Console.WriteLine("Reservation rejected: full.");
}
Console.WriteLine($"After rejection: {counter.Count}");
counter.Release();
Console.WriteLine($"After release: {counter.Count}");
public class BookingCounter
{
public int Count { get; private set; }
public void Reserve()
{
if (Count == 2)
throw new InvalidOperationException("No places remain.");
Count++;
}
public void Release()
{
if (Count == 0)
throw new InvalidOperationException("No booking to release.");
Count--;
}
}Reservation rejected: full. After rejection: 2 After release: 1
The third call throws at the check, before Count++ runs.
The starting count is zero. Every available change preserves the allowed range. Callers cannot write counter.Count = -10 because they cannot access its setter.
flowchart TD
C["Caller"] -->|"calls"| M["Reserve or Release"]
M -->|"checks before change"| S["Private writable state"]
The caller requests an operation; the object decides whether that operation is allowed.
The mistake to avoid. A private setter does not perform validation for you. The class must check every path that changes the property.
In an interview, say: “Encapsulation means the object protects its own rules. I keep state private or privately writable, then expose operations that validate a change before making it.”
Protected access: OR, AND, and the receiving object
Consider a public base class named Worker in a library and a derived class named RemoteWorker in another assembly.
If Worker.Reset() is protected internal, unrelated code inside the library can call it through the internal route. RemoteWorker can also call it through the protected route. Either condition is enough: same assembly OR derived class.
If Worker.Reset() is private protected, an unrelated library class cannot call it. Neither can RemoteWorker in another assembly. A class derived from Worker inside the library can call it. Both conditions are needed: same assembly AND derived class.
There is another restriction on protected instance members. The receiver is the object expression before the dot in a member access, such as worker in worker.Reset().
Inside RemoteWorker, protected access is allowed through this or a receiver whose declared type is RemoteWorker or a class derived from it. It is not allowed through an arbitrary variable declared as Worker.
That remains true even when the variable happens to hold a RemoteWorker object. The compiler checks the receiver's declared type. Access through a base-class variable fails with CS1540. This receiver restriction also applies when cross-assembly access uses the protected part of protected internal.
This example deliberately does not compile.
public class Worker
{
protected void Reset() { }
}
public class RemoteWorker : Worker
{
public void Check()
{
this.Reset(); // OK
RemoteWorker r = this; r.Reset(); // OK
Worker w = this; w.Reset(); // CS1540
}
}See Microsoft's protected access examples for the receiver rule.
The mistake to avoid. Protected access does not mean a derived class can inspect the protected state of every base-class object. The receiving object's declared type matters too.
In an interview, say: “Protected internal means same assembly OR derived class. Private protected means derived class AND same assembly. For protected instance access inside a derived class, I can use its own type or a further-derived type, not an arbitrary base-class variable.”
Why properties are usually better than public fields
A property gives you a place to control reading and writing without changing the caller's usual item.Size syntax.
You can start with a simple property and add checks later. You can also choose private set, as in the counter, or init. In the example below, the init-only property Label is set while the object is being created: new Package { Label = "Books", Size = 2 }. Neither choice automatically validates the assigned value.
Interfaces can declare properties. An interface cannot declare instance fields. This is one reason to expose data as properties.
C# 14 adds the contextual field keyword inside properties. It accesses the property's backing field, the storage used to hold that property's value. You can write a checking setter without declaring that field yourself.
This program uses C# 14 and runs on .NET 10. Predict the value of Size after the program tries to assign 0.
var item = new Package { Label = "Books", Size = 2 };
Console.WriteLine($"{item.Label}: {item.Size}");
try
{
item.Size = 0;
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Size rejected.");
}
Console.WriteLine($"Size remains: {item.Size}");
public class Package
{
public string Label { get; init; } = "Unnamed";
public int Size
{
get => field;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value));
field = value;
}
} = 1;
}Books: 2 Size rejected. Size remains: 2
Assigning zero throws before field is written.
Label can be assigned in new Package { ... }, but an ordinary later assignment to item.Label would not compile. This restricts reassignment; it does not check whether the label is meaningful.
Read about the syntax in What's new in C# 14.
The mistake to avoid. Do not assume a public field and a property are interchangeable for already compiled callers. Callers compiled against the field need recompiling if you replace it with a property.
In an interview, say: “I usually expose properties instead of public fields because properties give me a place for checks and controlled writing. I can use private set or init, and interfaces can declare properties. That flexibility does not mean every property needs a custom setter.”
Expose a list without exposing its changes
A read-only collection interface limits which operations callers can use through that interface. It does not necessarily protect the underlying list.
IReadOnlyList<T> lets callers read elements and a count without offering methods such as Add.
Returning a List<string> as IReadOnlyList<string> returns a reference to the same list. Callers can cast this object back to List<string> and change it.
There are three choices:
| Return choice | What the caller receives | Trade-off |
|---|---|---|
The list as IReadOnlyList<T> | The original list through a restricted interface | No protection against casting back to the list. |
list.AsReadOnly() | A read-only wrapper around the list | Blocks changes through the wrapper, but reflects later changes to the original list. |
| A copy | A separate collection containing the current elements | Copying takes work and storage; later additions to the original are not visible. |
Predict which counts change after adding "Second" through Add.
var notes = new Notes();
notes.Add("First");
var leaked = (List<string>)notes.UnsafeItems;
leaked.Add("Bypassed Add");
Console.WriteLine($"After cast-back change: {notes.Items.Count}");
var view = notes.Items;
var snapshot = notes.Snapshot();
Console.WriteLine($"Wrapper is a List: {view is List<string>}");
notes.Add("Second");
Console.WriteLine($"Live view: {view.Count}; snapshot: {snapshot.Length}");
public class Notes
{
private readonly List<string> _items = new();
public IReadOnlyList<string> UnsafeItems => _items;
public IReadOnlyList<string> Items => _items.AsReadOnly();
public string[] Snapshot() => _items.ToArray();
public void Add(string text)
{
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentException("A note needs text.", nameof(text));
_items.Add(text);
}
}After cast-back change: 2 Wrapper is a List: False Live view: 3; snapshot: 2
The cast succeeds because UnsafeItems returns the actual list. Its count becomes two without calling the checking method. The example deliberately exposes that unsafe property to demonstrate the problem; a real Notes class should remove it.
Items returns a wrapper, not a List<string>, so the same cast-back route does not work. That view follows the original list, so its final count is three. The snapshot stays at two.
The field uses readonly. On this field, that prevents replacing _items after construction; it does not prevent changing the list's contents.
See List<T>.AsReadOnly for the wrapper's behavior.
The mistake to avoid. A read-only interface does not make the object behind it unchangeable. Returning the original list still lets callers recover that list and bypass your checks.
In an interview, say: “Returning a List as IReadOnlyList only restricts the visible operations; callers can cast back. AsReadOnly returns a wrapper that reflects later changes. A copy gives a snapshot, at the cost of copying, and callers can change their copy without changing my list.”
Check yourself
Which statement correctly describes protected internal and private protected?
Show answer
Correct answer: B
protected internal permits access through the same-assembly route or the protected route. private protected permits derived-class access only within the same assembly.
A property returns its private List<string> directly as IReadOnlyList<string>. What can a caller do?
Show answer
Correct answer: B
The returned object is still the original List<string>. The interface does not provide Add, but a successful cast back to List<string> exposes it.
Going deeper
Accessibility must agree across declarations. A public class cannot derive from an internal base class; that produces CS0060. A public method on a public class cannot return an internal type; that produces CS0050. Making a method public does not make its return type accessible. Parameter types must also be at least as accessible as the method. The short interview answer is in C# OOP interview questions and answers.
Does a property initializer call the setter? Predict whether the setter message appears before or after Initial size: 1.
var check = new InitializerCheck();
Console.WriteLine($"Initial size: {check.Size}");
check.Size = 2;
Console.WriteLine($"After assignment: {check.Size}");
public class InitializerCheck
{
public int Size
{
get => field;
set
{
Console.WriteLine("Setter called.");
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value));
field = value;
}
} = 1;
}Initial size: 1 Setter called. After assignment: 2
In this check, = 1 supplies the initial size without calling the setter. The later assignment calls it. The Package.Size declaration uses the same initializer pattern. Changing that initializer to = 0 would create an invalid starting size without throwing. Assignments in an object initializer, such as new Package { Size = 2 }, do call the setter. Keep declaration-time defaults valid, or route construction through a checking assignment. The C# specification's property rules say a property initializer sets the backing field directly.
Collection protection has limits. The wrapper prevents changes through the wrapper; it does not stop the owning class from changing the list. Each AsReadOnly() call in the example creates a wrapper, so frequently read properties can retain and reuse one wrapper instead. A copied collection also does not copy every object inside it. If elements are changeable objects, both collections can still refer to those same objects.
Version details matter. private protected arrived in C# 7.2, init in C# 9, file in C# 11, and the property field keyword in C# 14. See the C# version history.
Sources
- Access Modifiers - C# | Microsoft Learn: Assembly definition, access levels and defaults, struct restrictions, and consistency requirements for exposed types.
- protected - C# Reference: Protected instance-member receiver restrictions and CS1540.
- What's new in C# 14: C# 14 field-backed property syntax.
- The field keyword: C# 14 introduction, compiler-provided property storage, and checking setters.
- file - C# reference: File-local types and the restriction on combining file with access modifiers.
- Friend assemblies: InternalsVisibleTo and access to internal members from a named assembly.
- List<T>.AsReadOnly Method: Read-only wrapper behavior and visibility of changes to the underlying list.
- The history of C#: Version milestones for private protected, init, and file.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 30 Nov 2026 ·