using System;
namespace AccessModifiersExample
{
public class Person
{
// Public member accessible from anywhere
public string Name { get; set; }
// Private member accessible only within the Person class
private int age;
// Protected member accessible within Person and derived classes
protected string Address { get; set; }
// Internal member accessible within the same assembly
internal string Nationality { get; set; }
// Protected internal member accessible within the same assembly and by derived classes
protected internal string Email { get; set; }
// Public constructor
public Person(string name, int age, string address, string nationality, string email)
{
Name = name;
this.age = age;
Address = address;
Nationality = nationality;
Email = email;
}
// Public method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {age}, Address: {Address}, Nationality: {Nationality}, Email: {Email}");
}
// Protected method
protected void DisplayProtectedInfo()
{
Console.WriteLine($"Address: {Address}");
}
// Internal method
internal void DisplayInternalInfo()
{
Console.WriteLine($"Nationality: {Nationality}");
}
// Protected internal method
protected internal void DisplayProtectedInternalInfo()
{
Console.WriteLine($"Email: {Email}");
}
}
// Derived class
public class Employee : Person
{
// Public member specific to Employee
public int EmployeeID { get; set; }
// Public constructor
public Employee(string name, int age, string address, string nationality, string email, int employeeID)
: base(name, age, address, nationality, email)
{
EmployeeID = employeeID;
}
// Public method
public void DisplayEmployeeInfo()
{
// Accessing protected and protected internal members from the base class
Console.WriteLine($"Employee ID: {EmployeeID}, Name: {Name}, Address: {Address}, Email: {Email}");
}
}
class Program
{
static void Main()
{
// Creating an object of the Employee class
Employee emp = new Employee("John Doe", 30, "123 Main St", "American", "john.doe@example.com", 12345);
// Accessing public members
Console.WriteLine(emp.Name);
Console.WriteLine(emp.EmployeeID);
// Accessing internal member
Console.WriteLine(emp.Nationality);
// Calling public method
emp.DisplayInfo();
emp.DisplayEmployeeInfo();
// Calling protected internal method
emp.DisplayProtectedInternalInfo();
// The following line would cause a compilation error because age is private
// Console.WriteLine(emp.age);
// The following line would cause a compilation error because Address is protected and cannot be accessed directly from an instance of Employee
// Console.WriteLine(emp.Address);
}
}
}