Question

C# deliberately prevents me from putting the internal access modifier on interface members. I'm pretty sure they had to put additional effort into implementing this restriction when they could have allowed it just as well.

There should be a good reason to spend that effort - which one?

For me it would be useful to have internal access modifiers on interfaces to realize "mutability prevention from the outside". E.g. consider the following interface:

interface IMessage
{
    ...
    DateTime LastSentTimestamp { get; internal set; }
    ...
}

Internally, within my message broker, I would like to be able to set the LastSentTimestamp. External users of my API should not be able to change it. Of course I could ditch the interface and use a class instead, however, this removes all the pros of interfaces (e.g. change implementation anytime, etc.)

Q1: I don't get it why they restrict me. Is there a particular reason?

Q2: I'm looking for a workaround for my particular situation above. Splitting the interface in two (IMessage and IInternalMessage) looks like a big pain in the ass and is hopefully not my only option left...

Was it helpful?

Solution

I guess the conflict that the C# designers have seen was that you cannot implement an interface with an internal member outside of the declaring assembly (and friend assemblies). Of course, it could still be useful to do this if outside assemblies only consume the interface. On the other hand you can get this behavior with a second internal-only interface:

public interface IPublic { /* all public members */ }
internal interface IPrivate : IPublic { /* additional members */ }

And your own classes implement IPrivate. External code can only use IPublic.

OTHER TIPS

It's not your interfaces' members which should have access modifiers but the overall interface, so as to have consistent accessibility, and your classes. Interfaces only get used when implemented by a class. Interfaces express a contract which must be realized by an implementer. How would a class implement your internal member if it lived outside the interface's assembly? Thereby it is unable to implement the contract, but classes within must be able to...that's logically inconsistent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top