Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must methods implementing internal interfaces be public

Tags:

c#

c#-4.0

I am developing an internal class that implements an internal interface. Can anyone explain why I cannot declare my method as internal, why I am getting the following error: "cannot implement an interface member because it is not public".

I know that I have to declare the method as public, but it makes absolutely no sense to me.

What is the point of declaring a method public if both the interface and the class are internal? Is it not misleading?

I have read a related question on this site. It is not an exact duplicate, because my class is internal.

like image 558
Arne Lund Avatar asked Jun 22 '12 18:06

Arne Lund


2 Answers

Simply put: because that's the way the language designers designed it. Even in internal interfaces, the methods are implicitly public. It does make things simple, but it's a pain in other ways.

If you want a public class where you want to "hide" the use of an internal interface, you could use explicit interface implementation - although that has other drawbacks.

Of course, if your class is internal then it doesn't matter that the methods are public anyway - other assemblies aren't going to be able to call the methods because they can't see the type.

I definitely agree that C# (or .NET in general) hasn't been designed as carefully as it might be around internal interfaces.

In terms of exactly why you're getting an error message - section 13.4.4 of the C# 4 spec (interface mapping) is the reason. Implementations are only found for nonstatic public members and explicit interface member implementations - and if there are any unimplemented members in the interface, an error occurs.

like image 172
Jon Skeet Avatar answered Nov 09 '22 16:11

Jon Skeet


I know this is old but maybe someone find it useful. You can accomplish a kind of internal interface methods like this:

internal interface IFoo
{
    void MyMethod();
}

public abstract class Foo : IFoo
{
    void IFoo.MyMethod()
    {
        MyMethod();
    }

    internal abstract void MyMethod();
}

So all your internal classes should derive from Foo and are forced to implement the abstract MyMethod. But you can treat them all as IFoo of course. But those classes outside the assembly won't provide the MyMethod class.

So you have the advantage to treat your classes internally as IFoo and rely on MyMethod. The drawback is that all your classes will need to derive from Foo which can be a problem if you need another base class.

But I found it helpful if the abstract base class is a generic one and the interface is not. Maybe it is useful in some cases.

like image 26
Robert S. Avatar answered Nov 09 '22 17:11

Robert S.