Search code examples
c#interfacepublicinternal

Problem with Interfaces


I have an interface(call it as IMessage) which has a method Check(), a class implements this interface

interface IMessage
{
    bool Check();
}

class NewClass : IMessage
{
    #region IMessage Members

    public bool Check()
    {
        //Some logic
    }
}

That all fine. The problem is that I don't want this method(Check()) to be public, I want to keep it internal to the asssembly, but if i make it internal then compiler says it doesn't implement the interface. It needs to be public to implement the interface. What can I do?


Solution

  • You can implement an interface method without making it part of the class's direct public interface by using explicit interface implementation syntax ( removing the access qualifier and prefix the interface name to the method ):

    interface IMessage
    {
        bool Check();
    }
    
    class NewClass : IMessage
    {
        bool IMessage.Check()  { }
    }
    

    However, anyone who can cast to the IMessage interface can still call Check(). This is not a way of preventing a call to the method - only of decluttering the public interface of the class. If the interface is internal to your assembly, then only classes in that assembly could cast to it and call the method.

    In general, .NET does not offer a way to make only certain method of an interface internal to an implementation of the interface. This is one area where you may want to consider an abstract base class - there you can create protected abstract methods which inheritors can implement without exposing them to external callers. For example:

    abstract class MessageBase
    {
        protected abstract bool Check();
    }
    
    class NewClass : MessageBase
    {
        protected override bool Check() { ... }
    }