Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 182 ยท Classes and Objects

Access Modifiers and Encapsulation

Learn C# access modifiers - public, private, protected, internal, protected internal, private protected and file - and how encapsulation keeps objects valid and code easy to change.

Every class you write has two faces. The inside is the data and the helper code that make it work. The outside is the small set of members that other code is allowed to use. Access modifiers are the keywords that draw the line between the two. They answer a single question for every type and member: who is allowed to see this?

This matters far more than it looks. Anything you make visible becomes a promise: other code will start to depend on it, and you can never change it freely again. Anything you keep hidden stays yours to rename, rewrite or delete. Good C# design is mostly the art of exposing as little as possible, and this lesson shows the seven levels you can choose from, the defaults the compiler picks for you, and how to use them for encapsulation: objects that protect their own rules.

The idea: hide the details, expose the behavior

Imagine a bank account whose balance is a public field. Any code anywhere can write account.Balance = 1_000_000;, and the account has no way to object. Now imagine the balance is private and the only way to change it is a Withdraw method that refuses to go below zero. The rules live in one place, and nobody can break them by accident.

C# A field anyone can break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The account now holds a negative balance, and it never had a chance to say no. Let us fix it by hiding the field.

C# Encapsulated account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The class is now in charge of its own invariant (a fact that must always be true, here "the balance never goes negative"). That is encapsulation: data and the rules for changing it live together, and the data is hidden behind a controlled surface. The Balance property you see here is the topic of Properties; for now read => as "this member returns...".

The seven access levels

C# has these modifiers. Ordered from most open to most hidden:

Modifier Who can use the member
public Any code, anywhere
protected internal Code in the same assembly or any subclass (even in another assembly)
internal Code in the same assembly
protected The class itself and its subclasses
private protected The class itself and subclasses in the same assembly
private Only the class (or struct) that declares it
file Only the same source file (types only)

An assembly is one compiled unit: a .dll or .exe, usually one project. Everything in this lesson's examples lives in a single assembly, so internal behaves like public when you run it here. The difference shows up as soon as your code is split across projects, as in a real solution with a library and an app.

public

A public member is part of your contract with the world. Use it for the operations you want to support for a long time. Public types in a library are very expensive to change, because you do not know who calls them.

private

Private is the default for members of a class or struct, and the right default for your thinking too. Fields, helper methods and anything that exists only to implement the public behavior should be private. The compiler enforces it:

C# Touching a private field (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops with main.cs(3,27): error CS0122: 'Counter._count' is inaccessible due to its protection level. The fix is not to make the field public, but to offer a method or a read-only property that returns what callers legitimately need.

internal

Internal means "visible inside this assembly". It is the default for top-level types (a class with no modifier is internal). Internal is perfect for the machinery of a library: classes that several files of the same project share but that you do not want to publish as API.

TEXT
MyLibrary.dll
  public  class PriceCalculator    <- callers in other projects can use it
  internal class TaxTable          <- only code inside MyLibrary.dll can use it

Because this is a layout of several projects, it cannot run in our one-file editor, so the snippet above is a diagram. If a test project needs to see your internals, the library can opt in with [assembly: InternalsVisibleTo("MyLibrary.Tests")] (a single attribute, often placed in the .csproj file instead). That is a concept worth knowing: it lets you test internal code without making it public, but do not use it as an excuse to expose everything.

protected

Protected members are visible to the class and to classes derived from it, but not to ordinary outside code. They are the extension points of an inheritance hierarchy.

C# Protected members and subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Code outside both classes cannot write sensor.Offset or sensor.ReadRaw(); it gets the same CS0122 as before. Think carefully before making anything protected: every protected member is a public promise to subclass authors, who are also outside code. Inheritance explains when subclassing is a good idea at all.

The two combined levels

protected internal is a union: allowed for subclasses or for anything in the same assembly. private protected is an intersection: allowed only for subclasses that are also in the same assembly. In practice:

  • protected internal is rare. It suits a hook that your own library calls from many places and that outside subclasses may override too.
  • private protected is useful when you design a hierarchy inside your own assembly and want to stop third parties from deriving their own classes and touching the guts.

You cannot see the difference in a single assembly, but both compile and run:

C# Combined modifiers in one assembly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

file

file (C# 11) applies to types only. A file type is visible only inside the source file that declares it. Two different files can each define a file class Helper without any clash. It is mostly useful for generated code and for private helper types in a large project. In the single-file editor it still compiles:

C# A file-scoped type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Defaults: what you get when you write nothing

If you leave the modifier out, C# picks the most restrictive sensible level for that position:

Where Default
Top-level class, struct, record, enum, interface, delegate internal
Member of a class, struct or record private
Member of an interface public
Member of an enum always public (you cannot write a modifier)
Nested type private

Write the modifier anyway on anything public-facing. It documents your intent, and many teams enforce it with an analyzer. An explicit private on fields is also common for readability, although not required.

Two rules the compiler enforces

A member can never be more visible than its type. If internal class Engine has a public method, the method is effectively limited to the assembly, because nobody outside can name Engine in the first place.

A public signature can only mention types that are at least as visible. This fails:

C# Exposing a less visible type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The error is error CS0050: Inconsistent accessibility: return type 'Product' is less accessible than method 'Shop.Cheapest()'. Product is internal by default while Shop and its method are public, so an outside caller would hold a value of a type it is not allowed to name. Make Product public or make Shop internal.

Encapsulation in practice

Hiding fields is the start. The skills that make encapsulation pay off:

1. Validate at the boundary. Constructors and setters are the only doors into the object. Check there, and the rest of the class can trust its own state.

2. Do not leak mutable internals. A private list is not private if a public property hands it out.

C# Leaking a private list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

IReadOnlyList<string> is a read-only view: callers cannot add or remove through it, although a determined caller could cast it back to List<string>. If that matters, return a copy (_members.ToArray()) or an immutable collection; Immutable Collections covers the options.

3. Prefer methods that express intent. account.Withdraw(30) says what happens; account.Balance -= 30 leaves the rule to the caller. Make it easy to do the right thing and impossible to do the invalid thing.

4. Keep the public surface small. Each public member is a long-term commitment. You can always make something more visible later without breaking anyone; making it less visible breaks callers.

Start with the narrowest modifier that compiles. Widen it only when a real caller needs it. It is much cheaper to promote a private method to public than to retire a public one that other teams already use.

Properties as the usual gateway

Rather than public fields, C# programs expose properties, which look like fields to callers but can hold logic and have separate read and write access levels:

C#
public string Name { get; private set; } = "";   // anyone can read, only this class can write
public int Id { get; init; }                     // set once, in an object initializer or constructor

Different accessors can carry different modifiers (here private set), as long as the accessor is more restrictive than the property itself. The full story is in Properties. Setting up a good object from the start is covered in Constructors and Object Initialization.

Common mistakes

  • Making fields public "to keep it simple". It is simple until the first bug that needs a breakpoint on every write.
  • Leaving everything public by habit. Public by default means your whole class is the API.
  • Mistaking internal for safe. internal hides from other assemblies, but the entire assembly can still reach in. Inside a big project, private is the real protection.
  • Using protected fields. Protected fields give subclasses direct write access to your state, which defeats your invariants. Use a protected method or property instead.
  • Thinking accessibility is security. Reflection can read private members. Access modifiers are a design tool that stops mistakes, not a way to hide secrets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default accessibility of a field declared in a class with no modifier?

    Members of classes and structs are private by default. Top-level types are internal by default.
  2. 2. Which modifier allows access from the same assembly or from any subclass, even in another assembly?

    protected internal is the union of protected and internal. private protected is the intersection (subclass AND same assembly).
  3. 3. What does the compiler do with a public method that returns an internal type?

    A public signature may only mention types that are at least as accessible as the member. Otherwise you get CS0050.
  4. 4. Why is returning a private List<string> from a public property a leak?

    The caller receives a reference to the same list, so Add, Remove and Clear work on the class's internal state. Return IReadOnlyList<T>, a copy or an immutable collection.
  5. 5. Which statement about the file modifier is true?

    file (C# 11) works on types only. Two files can each declare a file type with the same name without conflict.

Summary

  • Access modifiers decide who may use a type or member; expose as little as possible.
  • private (class members) and internal (top-level types) are the defaults.
  • protected is for subclasses, private protected is subclass AND same assembly, protected internal is subclass OR same assembly, file limits a type to its source file.
  • A member cannot be more visible than its type, and a public signature cannot use less visible types (CS0050).
  • Encapsulation means private data plus public behavior that protects invariants; never hand out mutable internals.
  • Access modifiers prevent mistakes; they are not a security boundary.

Next: Inheritance