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 a requirement where a method you are implementing, must be public. The error thrown is usually “Cannot implement an interface member because it is not public”.

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

But methods have to be either 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.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: