Search code examples
c#oopinheritanceprotectedaccess-modifiers

How to access to a function whose access modifier is protected and exists in a class that inherits from another class in c#?


public class a
{
    protected virtual int mult(int x)
    {
        return x * x;
    }
}

public class b : a
{
    protected override int mult(int x) { return x * x * x; }
}

internal class Program
{
    static void Main(string[] args)
    {
        b jack = new b();
        int v = jack.mult(5);    // error

        // so how can I access mult() in the main class without changing the access modifier to public ??????
    }
}

How to access a function whose access modifier is protected and exists in a class that inherits from another class in c#?


Solution

  • Note that the mult function is declared as protected in both class a and class b, which means that it can only be accessed by code within the class or its derived classes. Since b is a derived class of a, the mult function is accessible to code within b.

    If you want to access the mult function from a class other than b or a subclass of b, you will need to change the access modifier to the public or provide a public method in b or a subclass of b that calls the mult function.

    In this case you are doing all this in the Main method which is in other class than a or b.