C# : Cannot implement an interface member because it is not public

If you've written a class that has implemented an interface, you've probably encountered the requirement where a method you are implementing, must be public. The error throw is usually “Cannot implement an interface member because it is not public”.

By default if an interface member method is implemented in your class without an access modifier, it is by default private.

But methods have to be public so that they can be called through the interface or they need to be explicit. Let us assume your interface is implemented as follows:

public interface ITest 
{
bool IsTest();
}

To change the visibility, you can either change the interface from public to internal.

or you can do explicit interface implementation. Explicit implementation hides the class member so it can only be accessed through the interface.  All you have to do is prefix the member with the interface name, as demonstrated here:

public class Test: ITest
{
bool ITest.IsTest() { return true; }
}

..in which case this method will be available only via the interface ITest. This way to implement the method explicitly also hides these methods from intellisense.

Please note that this requirement is only in C# where it requires that implicit interface implementations must be public. In VB.NET you do not require an explicit accessibility keyword.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: