Search code examples
c#interfaceaccess-specifier

Why can't interface members be non-public?


Possible Duplicate:
Non Public Members for C# Interfaces

Suppose I have

internal interface IInterface
{
    int MyProperty { get; set; }
}

public class MyClass : IInterface
{
    internal int MyProperty
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
}

I get this:

does not implement interface member; cannot implement an interface member because it is not public;

I know what's the fix, but I am wondering why doesn't C# let interface members to be private.

Many times over I wanted my classes to follow a pattern, but needn't expose the members to public, say when I am writing a library. And best of all, the Interface itself is not public :X

Note: I am not asking how to implement private interface members, but I am knowing the design logic that went behind this decision. I couldn't find a suitable duplicate.

Update: More than the original thread, this code sample from the answer in another thread explains it better than most description answers. Or even better, from @JonSkeet this


Solution

  • An interface is used to define a contract, by making the fields/methods private there is really no point in using an interface then. How does the client know how to use the contract? Unless you really need an abstract class.