Tuesday, June 30, 2026

C# How to access protected implemented method of interface

Since C#8.0, default implemented method is allowed. This allows for different access modifiers (e.g. public, private, protected) with default method. The question is- how to access protected method in implementing class?
interface ILogger
{
    protected void Print()
    {
        Console.WriteLine("Protected member");
    }
}

class MyLogger : ILogger
{
    public void GetProtected()
    {
        ILogger logger = new MyLogger();
    }
}

Answer: In C# (default interface methods, C# 8+), a protected method inside an interface is not accessible from the implementing class instance directly.

In above code, Print() is protected inside the interface, which means:

  • It is available only to derived interfaces, not implementing classes.
  • MyLogger cannot call Print() directly.
  • Even ILogger logger = new MyLogger(); does not expose Print().
  • So this will not compile:

If you want implementing classes to access helper logic, use protected inside a public method. So, indirectly protected method can be accessed via public method.

Example:

interface ILogger
{
    protected void Print()
    {
        Console.WriteLine("Protected member");
    }
    public void Log()
    {
        Print(); // allowed inside interface
    }
}

class MyLogger : ILogger
{
    public void GetProtected()
    {
        ILogger logger = new MyLogger();
        logger.Log();
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyLogger logger = new MyLogger();
        logger.GetProtected();
    }
}
Note. The private and protected members in interfaces exists mainly for derived interfaces, not implementing classes. The private and protected members of interface are accessed indirectly via public member.

 

No comments:

Post a Comment

Hot Topics