๐ŸŽ“ A1Learner
๐Ÿ”

C# Access Modifiers

Access modifiers are keywords that control whether code outside a class can use a member. The two main modifiers are public and private.

A public field

The model field is public. Main reads it through the object.

using System;

class Car
{
    public string model = "Ford";
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        Console.WriteLine(myCar.model);
    }
}

Private field, public reader

The model field is private here. The public GetModel method reads it for Main.

using System;

class Car
{
    private string model = "Ford";

    public string GetModel()
    {
        return model;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        Console.WriteLine(myCar.GetModel());
    }
}

Reading a private field fails

Main reads the private model field directly here. The compiler refuses the program.

using System;

class Car
{
    private string model = "Ford";
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        Console.WriteLine(myCar.model);
    }
}

Example

using System;

class Account
{
    private int balance = 100;

    public void Deposit(int amount)
    {
        balance = balance + amount;
    }

    public int GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Account account = new Account();
        account.Deposit(50);
        Console.WriteLine(account.GetBalance());
    }
}

Key points

  • Use public to make a member usable from outside its class.
  • Use private to keep a member usable only inside its class.
  • A member is a field or a method inside a class.
  • A public method can read a private field of its own class.
  • The compiler refuses a read of a private field from outside code.

In this example, the balance field is private and starts at 100. Main cannot read the field directly. The public Deposit method adds 50 to the balance. The public GetBalance method returns the new total of 150.

Note

A class member with no modifier is private.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

Which modifier keeps a field usable only inside its own class?