Question

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?

Was it helpful?

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() { ... }
}

OTHER TIPS

Interfaces are all about how other objects interface with that type of object, in a public way. If other classes shouldn't access the Check() method, then that shouldn't be part of the interface.

Here's an MSDN discussion of this topic which may be helpful.

class NewClass : IMessage
{
    #region IMessage Members

    internal bool Check()
    {
        //Some logic
    }
    bool IMessage.Check()
    {
        return this.Check();
    }
}

This provides an internal implementation, only available to classes within that assembly, plus an explicit interface implementation that allows you to meet the requirements of the interface. For code from an outside assembly to call the Check method, it would require an IMessage reference to your class, not a NewClass reference.

Alternatively, you could use an abstract method on a base class:

public abstract class Message
{
    internal abstract bool Check();
}

public class MyMessage : Message
{
    internal override bool Check()
    {
        // do stuff
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top