C# Access Modifiers - Complete Guide
Introduction to Access Modifiers
Access modifiers in C# are keywords that determine the visibility and accessibility of types and their members. They are fundamental to encapsulation, one of the core principles of object-oriented programming, and help enforce controlled access to class data and behavior.
C# provides six access levels: public, private, protected, internal, protected internal, and private protected. Choosing the right access modifier improves code safety, readability, and maintainability.
Types of Access Modifiers
The following example demonstrates how different access modifiers work in C#:
Example
using System;
namespace AccessModifiersExample
{
// Public class - accessible from any assembly
public class Vehicle
{
// Public member - accessible from anywhere
public string PublicModel = "Generic Model";
// Private member - accessible only within this class
private string privateVIN = "ABC123XYZ";
// Protected member - accessible within this class and derived classes
protected int protectedYear = 2020;
// Internal member - accessible within the same assembly
internal string InternalColor = "Red";
// Public method to expose private data safely
public string GetVIN()
{
return privateVIN;
}
// Protected method
protected void DisplayProtectedInfo()
{
Console.WriteLine($"Year: {protectedYear}");
}
}
// Internal class - accessible only within the same assembly
internal class Car : Vehicle
{
public void DisplayCarInfo()
{
// Accessing protected member from base class
Console.WriteLine($"Car Year: {protectedYear}");
// Accessing internal member from base class
Console.WriteLine($"Car Color: {InternalColor}");
// Accessing public member from base class
Console.WriteLine($"Car Model: {PublicModel}");
// Calling protected method from base class
DisplayProtectedInfo();
}
}
class Program
{
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle();
Car car = new Car();
// Accessing public members
Console.WriteLine($"Vehicle Model: {vehicle.PublicModel}");
Console.WriteLine($"Vehicle VIN: {vehicle.GetVIN()}");
Console.WriteLine("\nCar Information:");
car.DisplayCarInfo();
// Demonstrating access restrictions (would cause errors if uncommented):
// Console.WriteLine(vehicle.privateVIN); // Error: private
// Console.WriteLine(vehicle.protectedYear); // Error: protected
// vehicle.DisplayProtectedInfo(); // Error: protected
// Internal member accessible within same assembly
Console.WriteLine($"\nVehicle Color (internal): {vehicle.InternalColor}");
}
}
}
Output
Vehicle Model: Generic Model Vehicle VIN: ABC123XYZ Car Information: Car Year: 2020 Car Color: Red Car Model: Generic Model Year: 2020 Vehicle Color (internal): Red