Start learning free

LESSON 632 OF 674 · OBJECT-ORIENTED PROGRAMMING

Access Modifiers in C#

Lesson

TL ; DR:

  • An access modifier controls who can see a member of a class. The two you'll use most are public (anyone) and private (only this class).


  • Make data private so callers can't break invariants by writing to it. Expose what they need through public methods:

    class Dog {
        private string name;        // hidden from outside
    
        public Dog(string name) {   // anyone can construct
            this.name = name;
        }
    
        public string GetName() {   // controlled read access
            return name;
        }
    }
    

  • Outside the class, rex.name is a compile error. Use rex.GetName() instead.



Full lesson:

So far every field we wrote was public — anyone could read or write it. That's convenient, but it leaks the class's internals. If you later decide to validate the data or compute it differently, every caller in the codebase breaks.


Encapsulation

Encapsulation is the idea that an object's data should be hidden behind methods. The class controls how it's read and written; outside code only sees the API.

class Account {
    private decimal balance;

    public void Deposit(decimal amount) {
        if (amount < 0) throw new ArgumentException();
        balance += amount;
    }
}

If balance were public, anyone could write account.balance = -1000; and break the invariant.


The two main modifiers

publicVisible everywhere.
privateVisible only inside the same class.

(There are also protected and internal, which we'll cover when we get to inheritance and assemblies.)


Your task

The Dog class's name field is now private. Add a public string GetName() method that returns it, so the harness in Solution.MainFunction can read the dog's name.

Dog's name: Rex
STEP 1 OF 2
    Ctrl + Enter to check