Sunday, June 28, 2026

C# How to use private method implemented in an interface type

We know that we cannot use private member outside its own type. The private member can be consumed only inside its own type. This is true for interface as well. Let us consider the following code. Since Print method is not consumed inside ICommon interface, it is useless. Then how to use a private method inside an interface? We can use private method as a helper method.
interface ICommon
{
    private void Print()
    {
        Console.WriteLine("C#8 onward access modifier allowed.");
    }
}

class Test : ICommon { }
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
    }
}
Example
We can create private method inside an interface as a helper method. 
interface ILogger
{
    void LogInfo(string msg)
    {
        Write("INFO", msg);
    }

    void LogError(string msg)
    {
        Write("ERROR", msg);
    }

    // shared helper
    private void Write(string type, string msg)
    {
        Console.WriteLine($"[{type}] {msg}");
    }
}

class MyLogger : ILogger { }

class Program
{
    static void Main()
    {
        ILogger logger = new MyLogger();

        logger.LogInfo("Started");
        logger.LogError("Failed");
    }
}
OUTPUT
[INFO] Started
[ERROR] Failed

No comments:

Post a Comment

Hot Topics