Search code examples
c#oopinheritanceinterfaceabstract

Restricting child class from accessing parent class methods


I have 3 departments/classes Employee, Account and Admin. In Employee department we have three properties -: "EmployeeID", "EmployeeName", "Salary".

Requirement-:

Account department can access all the three properties("EmployeeID", "EmployeeName", "Salary") from Employee department whereas Admin department can only access properties ("EmployeeID" ,"EmployeeName"). We have to restrict Admin Department from accessing property("Salary") from Employee Department.

How can we implement the above mentioned real life concept in C# programming.

I was trying using inheritance but could not get any solution.

class Employee
{
    public int EmployeeId = 123;
    public string EmployeeName = "Ram";
    public double salary = 50000;
}
class Account : Employee
{
    

}
class Admin : Account
{

}
public class Demo
{
    public static void Main(string[] args)
    {
        Account ac = new Account();
        Console.WriteLine("EmployeeID= {0}", ac.EmployeeId);
        Console.WriteLine("EmployeeName= {0}", ac.EmployeeName);
        Console.WriteLine("EmployeeSalary= {0}", ac.salary);

        Admin ad = new Admin();
        Console.WriteLine("EmployeeID= {0}", ad.EmployeeId);
        Console.WriteLine("EmployeeName= {0}", ad.EmployeeName);

        //  requirement is salary property should not be accesssible to the admin object;
        Console.WriteLine("EmployeeSalary= {0}", ad.salary);


    }
}

}


Solution

  • I think you are mixing up different concerns here. C# access modifiers, i.e. public/private etc, is intended to make your code more readable and modular.

    Preventing Admin users from accessing "Salaries" is a business requirement that are usually not mapped directly to code. One option would be to have an account type enum:

    public enum EmployeeType{
        Employee,
        Account ,
        Admin 
    }
    

    This lets you check the account type whenever you want to allow the user to do anything:

    var myEmployeeType= ...
    switch(myEmployeeType){
        case EmployeeType.Account:
            Console.WriteLine("EmployeeID= {0}", ac.EmployeeId);
            Console.WriteLine("EmployeeName= {0}", ac.EmployeeName);
            Console.WriteLine("EmployeeSalary= {0}", ac.salary);
        break;
        ....
    }
    
    

    Note that any checks done on the local machine can probably be circumvented by a skilled user. Anything that is important for security needs to be checked and controlled on a server that you have control over. A typical solution would be a web server that does all the user management and security checks, and uses a private database for storage.