Access Modifier
Access Modifier
In this tutorial, we will learn about the public, private, protected, and internal access modifiers in C#
with the help of examples.
In C#, access modifiers specify the accessibility of types (classes, interfaces, etc) and type members
(fields, methods, etc). For example,
class Student {
}
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
namespace MyApplication {
class Student {
public string name = "Sheeran";
class Program {
static void Main(string[] args) {
namespace MyApplication {
class Student {
private string name = "Sheeran";
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
In the above example, we have created a class named Student with a field name and a
method print().
// accessing name field and printing it
Console.WriteLine("Name: " + student1.name);
namespace MyApplication {
class Student {
protected string name = "Sheeran";
}
class Program {
static void Main(string[] args) {
namespace MyApplication {
class Student {
protected string name = "Sheeran";
}
// derived class
class Program : Student {
static void Main(string[] args) {
namespace Assembly {
class Student {
internal string name = "Sheeran";
}
class Program {
static void Main(string[] args) {
namespace Assembly1 {
class Program {
static void Main(string[] args) {
}
}
}
Here, this code is in Assembly1. We have created an internal field name inside the
class StudentName. Now, this field can only be accessed from the same assembly Assembly1.
Now, let's create another assembly.
// Code on Assembly2
using System;
// access Assembly1
using Assembly1;
namespace Assembly2 {
class Program {
static void Main(string[] args) {
StudentName student = new StudentName();
namespace Assembly1 {
public class Greet {
protected internal string msg="Hello";
}
class Program {
static void Main(string[] args) {
Greet greet = new Greet();
Console.WriteLine(greet.msg);
Console.ReadLine();
}
}
}
Output
Hello
The above code is in Assembly1.
In the above example, we have created a class named Greet with a field msg. Since the field is
protected internal, we are able to access it from the Program class as they are in the same assembly.
Let's derive a class from Greet in another assembly and try to access the protected internal
field msg from it.
// Code on Assembly2
using System;
// access Assembly1
using Assembly1;
namespace Assembly2 {
namespace Assembly1 {
public class StudentName {
private protected string name = "Sheeran";
}
namespace Assembly2 {