Compiler error ยท error CS0122

'X' is inaccessible due to its protection level

The member exists โ€” you just can't see it from here. private means "only this class", and you're standing outside it.

See it happen

class Account
{
    private int balance = 100;   // closed to the outside world
}

Account a = new Account();
Console.WriteLine(a.balance);    // not your business, says the compiler

The access levels, quickly

ModifierWho can see it
privateOnly code inside the same class
protectedThe class and classes that inherit from it
internalAny code in the same assembly/project
publicEveryone

Class members default to private when you write no modifier โ€” which is why "I never wrote private, but it's private" happens.

Fix 1: a method that exposes what you need

This is the right fix when the field should stay hidden but its value should be readable:

class Account
{
    private int balance = 100;

    public int GetBalance()      // public door to the private room
    {
        return balance;
    }
}

Account a = new Account();
Console.WriteLine("Balance: " + a.GetBalance());

Fix 2: a property (the idiomatic door)

class Account
{
    public int Balance { get; private set; } = 100;   // readable, not writable outside

}

Account a = new Account();
Console.WriteLine("Balance: " + a.Balance);

Here the property is the public face of the data, and private set means outside code can read a.Balance but never assign it. (The engine supports auto-properties; full-body getters with logic run in Visual Studio.)

Fix 3: make the field public โ€” when the design really is open

class Settings
{
    public int MaxRetries = 3;   // deliberately open data container
}

Settings s = new Settings();
Console.WriteLine(s.MaxRetries * 33 + 1);

Fine for simple data-holder classes. Not fine for objects with rules โ€” if balance must never go negative, a public field lets anyone break that.

Why not just make everything public?

Because private protects invariants. Consider an account where the balance must always equal the sum of its transactions:

class Account
{
    private int balance = 0;

    public void Deposit(int amount)
    {
        if (amount <= 0) throw new Exception("amount must be positive");
        balance += amount;                 // the only way in โ€” and it validates
    }
}

A public balance would allow a.balance = -500; from anywhere. The compiler error is the class saying "use the front door".

Frequently asked

What does CS0122 mean?

You accessed a member that isn't visible from where you are โ€” usually a private field from outside its class.

Should I make everything public?

No. Private protects invariants. Expose what callers legitimately need through a property or a validating method.

Checklist