C# Access Modifiers

In C#, access modifiers specify the accessibility of types (classes, interfaces, etc) and type members (fields, methods, etc). For example,

class Student {

  public string name;
    
  private int num;

  }

Here,

  • name - public field that can be accessed from anywhere

  • num - private field can only be accessed within the Student class

Types of Access Modifiers

In C#, there are 4 basic types of access modifiers.

  • public

  • private

  • protected

  • internal

1.Public Access Modifier

When we declare a type or type member public, it can be accessed from anywhere. For example,

using System;

class Student
{
    public string name = "Sheeran";

    public void print()
    {
        Console.WriteLine("Hello from Student class");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Student student1 = new Student();

        // accessing name field and printing it
        Console.WriteLine("Name: " + student1.name);

        Console.ReadLine();
    }
}

In the above example, we have created a class named Student with a field name and a method print(). Since the field and method are public, we are able to access them from the Program class.

2.Private Access Modifier

When we declare a type member with the private access modifier, it can only be accessed within the same class . For example,

using System;

class Student
{
    private string name = "Sheeran";

    public void print()
    {
        Console.WriteLine("Hello from Student class");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Student student1 = new Student();

        //error
        Console.WriteLine("Name: " + student1.name); 

        Console.ReadLine();
    }
}

In the above example, we have created a class named Student with a field name

Since the field and method are private, we are not able to access them from the Program class. Here, the code will generate the error.

3.Protected Access Modifier

When we declare a member as protected, it can only be accessed from the same class and its derived classes. More on this later.

4.Internal Access Modifier

When we declare a type or type member as internal, it can be accessed only within the same assembly.

An assembly is a collection of types (classes, interfaces, etc) and resources (data). They are built to work together and form a logical unit of functionality. That's why when we run an assembly all classes and interfaces inside the assembly run together. More on this later.

Last updated