Access Modifiers
Access Modifiers
Access modifiers in C# are used to specify the scope of accessibility of a member of a class or type of the class itself. For example, a public class is accessible to everyone without any restrictions, while an internal class may be accessible to the assembly only.
Private Access Modifier
Objects that implement private access modifiers are accessible only inside a class or a structure. As a result, we can’t access them outside the class they are created
using System;
namespace MyApplication {
class Course {
private string CourseName = "C#";
private void print() {
Console.WriteLine("Topics from C#");
}
}
class Program {
static void Main(string[] args) {
// creating object of Course class
Course course1 = new Course();
// accessing CourseName field and printing it
Console.WriteLine("CourseName: " + course1.CourseName);
// accessing print method from Course
course1.print();
Console.ReadLine();
}
}
}
OUTPUT
error CS0122: `MyApplication.Course.CourseName' is inaccessible due to its protection level
error CS0122: `MyApplication.Course.print()' is inaccessible due to its protection level
Public Access Modifier
Objects that implement public access modifiers are accessible from everywhere in our project. Therefore, there are no accessibility restrictions.
using System;
namespace MyApplication {
class Course {
public string CourseName = "C#";
public void print() {
Console.WriteLine("Topics from C#");
}
}
class Program {
static void Main(string[] args) {
// creating object of Course class
Course course1 = new Course();
// accessing CourseName field and printing it
Console.WriteLine("CourseName: " + course1.CourseName);
// accessing print method from Course
course1.print();
Console.ReadLine();
}
}
}
OUPUT
CourseName: C#
Topics from C#
Protected Access Modifier
The protected keyword implies that the object is accessible inside the class and in all classes that derive from that class. we are going to take a look at this example to understand the behavior of the protected members.
using System;
namespace MyApplication {
class Course {
protected string CourseName = "C#";
}
class Program {
static void Main(string[] args) {
// creating object of Course class
Course course1 = new Course();
// accessing CourseName field and printing it
Console.WriteLine("CourseName: " + course1.CourseName);
Console.ReadLine();
}
}
}
OUTPUT
error CS0122: `MyApplication.Course.CourseName' is inaccessible due to its protection level
Now, let's try to access the protected member from a derived class.
using System;
namespace MyApplication {
class Course {
protected string CourseName = "C#";
}
// derived class
class Program : Course {
static void Main(string[] args) {
// creating object of derived class
Program program = new Program();
// accessing CourseName field and printing it
Console.WriteLine("CourseName: " + program.CourseName);
Console.ReadLine();
}
}
}
OUTPUT
CourseName: C#