Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 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 file modifier, and the defaults.
    • Why protected internal means OR, while private protected means 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:

    ModifierWhich code can access it?
    publicCode anywhere, provided the containing type is accessible.
    privateCode within the containing class or struct.
    protectedCode within the containing class or a derived class, subject to the receiver rule explained below.
    internalCode in the same assembly.
    protected internalCode in the same assembly OR code in a derived class elsewhere.
    private protectedCode 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 modifierDefault
    Top-level class, struct, interface, or enuminternal
    Class or struct member, including a nested typeprivate
    Interface memberpublic
    Enum memberAlways 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.

    C#Runs
    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--;
        }
    }
    Output
    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.

    C#
    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.

    C#Runs
    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;
    }
    Output
    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 choiceWhat the caller receivesTrade-off
    The list as IReadOnlyList<T>The original list through a restricted interfaceNo protection against casting back to the list.
    list.AsReadOnly()A read-only wrapper around the listBlocks changes through the wrapper, but reflects later changes to the original list.
    A copyA separate collection containing the current elementsCopying takes work and storage; later additions to the original are not visible.

    Predict which counts change after adding "Second" through Add.

    C#Runs
    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);
        }
    }
    Output
    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?

    A Both allow only derived classes, and only inside the same assembly.
    B protected internal uses OR; private protected uses AND for derived-class access.
    C protected internal means derived classes only within the same assembly.
    D private protected also lets derived classes in other assemblies access the member.
    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?

    A Nothing that changes it, since IReadOnlyList<string> makes the list immutable.
    B Cast the result back to List<string> and change the original list.
    C Change only a private copy, because the property returns a new snapshot.
    D Call Add through IReadOnlyList<string>, which forwards it to the list.
    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.

    C#Runs
    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;
    }
    Output
    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

    Practice

    Practice test: Practice: Encapsulation and Access Modifiers in C#: Keep Objects Valid10 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    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 ·