In C#, when you implement an interface, all members are implicitly public. Wouldn't it be better if we could specify the accessibility modifier (protected
, internal
, except private
of course), or should we just use an abstract class instead?
-
9You can hide interface from API if you implement it explicitly. – epitka Aug 25 '10 at 20:11
-
Might be coming in C# 8.0 https://jeremybytes.blogspot.com/2019/11/c-8-interfaces-public-private-and.html – Doug Domeny Sep 22 '20 at 14:08
9 Answers
If an interface is internal, all its members will be internal to the assembly. If a nested interface is protected, only the subclasses of the outer class could access that interface.
Internal members for an interface outside of its declaring assembly would be pointless, as would protected members for an interface outside of its declaring outer class.
The point of an interface is to describe a contract between a implementing type and users of the interface. Outside callers aren't going to care and shouldn't have to care about implementation, which is what internal and protected members are for.
For protected members that are called by a base class, abstract classes are the way to go for specifying a contract between base classes and classes that inherit from them. But in this case, implementation details are usually very relevant, unless it's a degenerate pure abstract class (where all members are abstract) in which case protected members are useless. In that case, go with an interface and save the single base class for implementing types to choose.

- 16,580
- 5
- 54
- 111

- 98,437
- 31
- 224
- 236
-
what do you mean by "users of that interface"? So is that when you create a variable lets say IMyInterface someVar; And then use someVar somehow? – PositiveGuy Jul 08 '10 at 17:56
-
1Also I may add that Interfaces force a pattern / commonality to the structure of your application (the classes within) which is a hug point even if you're not exposing the interfaces to external clients...right?? – PositiveGuy Jul 08 '10 at 20:32
-
I would think it useful for interfaces to have `internal` members. If assembly Foo could contain an interface `IWoozle` with `internal` members, and if it contained five implementations of `IWoozle`, code anywhere could pass around instances of `IWoozle`, and use its public members, but code that received an `IWoozle` would know that it was implemented within assembly Foo. Consider, for example, hypothetical interface `IImmutableWoozle`. It's possible that implementations might not all share a common base type, but if no implementations could exist outside Foo, then... – supercat Jan 13 '12 at 00:06
-
...code in Foo, or which trusted that Foo wouldn't do anything nasty, could know that an `IImmutableWoozle` wasn't going to be some wacky mutable implementation. – supercat Jan 13 '12 at 00:07
-
In this case, you can create an internal interface, `IInternalWoozle`, that implements `IWoozle` and any code in Foo that uses any `IWoozle` can check if `IInternalWoozle` is also implemented in order to get at the internal members. The .NET framework does just this in places. – Mark Cidade Jan 13 '12 at 19:43
-
Interface members that are only accessible by the declaring assembly would necessitate some unnecessary scheme to map unimplemented `internal` members for when one of the assembly's types accesses `IWoozle.InternalMember` on implementations from outside of the assembly. – Mark Cidade Jan 13 '12 at 19:45
-
@MarkCidade: The problem with using a separate internal interface is that any routine which passes an `IInternalWoozle` to the outside world and gets it back would have to cast it to `IInternalWoozle` (and hope the cast succeeds). One could define a public struct `WrappedWoozle` with an `internal` member of type `IInternalWoozle`, and use that struct type when passing things to/from the outside world, but that would add an extra layer of boxing in some cases. – supercat Sep 13 '12 at 22:57
-
If it's important to the routine as to whether or not the object is an `IInternalWoozle`, then it can use the `as` operator to assign it to an `IInternalWoozle` variable and check first if it is null, in which case it can just ignore it. With a struct that has an internal member, you would still have to check for null. – Mark Cidade Sep 15 '12 at 01:10
-
If an interface is internal, all its (public) members **will NOT be** internal to the assembly. Even if it did, that destroys the very idea of public! – nawfal Sep 24 '12 at 11:02
You can hide the implementation of an interface by explicitly stating the interface name before the method name:
public interface IInterface {
public void Method();
}
public class A : IInterface {
public void IInterface.Method() {
// Do something
}
}
public class Program {
public static void Main() {
A o = new A();
o.Method(); // Will not compile
((IInterface)o).Method(); // Will compile
}
}

- 1,467
- 2
- 13
- 20

- 56,243
- 7
- 59
- 69
-
2Just a comment: nowadays you cannot use the `public` modifier in an interface member or a explicitly implemented interface method. For your code to work with .NET 4.5 for example, simply both `public`s should be removed. – Andrew Jul 05 '15 at 03:34
-
-
Why wouldn't `o.Method()` compile? Can someone explain this? Why does stating the interface name hide the interface implementation? – Kyle Delaney Jan 26 '17 at 18:54
-
Kyle. This notation (implementing the method with the interface name) is called explicit interface implementation and I think, its purpose is to hide the method from outside called (except casting explicitly then calling). This is very useful for some cases. For example, the base class may perform a one time only operation in the implementation of the interface method. If the method is visible to outside callers, they may call the method more than once and break the base class's working state. – Xtro Oct 27 '17 at 13:24
All the answers here more or less say that's how interfaces are meant to be, they are universal public specifications.
This being the most discussed thread, let me post two excellent answers I found on SO when this question surfaced my mind.
This answer gives an example of how it can be nonsensical to have non uniform access specifiers for interface members in derived classes. Code always better than technical descriptions.
To me the most damning thing about forced public interface members are that the interface itself can be internal to an assembly but the members it exposes have to be public. Jon Skeet explains here that's by design sadly.
That raises the question why weren't interfaces designed to have non-public definitions for members. That can make the contract flexible. This is pretty useful when writing assemblies where you dont want specific members of classes to be exposed to outside the assembly. I do not know why.
Would not make sense. An Interface is a contract with the public that you support those methods and properties. Stick with abstract classes.

- 14,138
- 9
- 71
- 83
-
6An 'internal' access modifier would seem a perfectly useful thing for interfaces to have; an interface which has such a modifier on any of its members could only be implemented by code within the assembly wherein it is declared, but could be used by code anywhere. I can see plenty of uses for that. – supercat Jan 12 '12 at 23:58
-
1I don't think interfaces are meant to be used as strongly-typed guidelines or scaffolding for code within the same assemblies. I believe their main purpose is "interfacing" with the outside world. – Ishmaeel Jan 17 '12 at 10:04
-
Suppose an assembly defines BankCheckingAccount, CreditUnionCheckingAccount, BankSavingsAccount, and CreditUnionSavingsAccount. Bank accounts have features lacking in credit-union accounts and vice versa. Checking accounts have features lacking in savings accounts and vice versa. It would be helpful to have types for checking accounts, savings accounts, bank accounts, and credit-union accounts, but one could only use abstract classes for two of those four. If inheritance of the abstract classes were limited to the same assembly... – supercat Jan 17 '12 at 15:52
-
...one could be assured that a CheckingAccount was either a BankCheckingAccount or a CreditUnionCheckingAccount, and wasn't a JoeHackerPhonyCheckingAccount. It would be helpful to be able to provide similar assurances for an IBankAccount interface (implemented by BankCheckingAccount and BankSavingsAccount) or an ICreditUnionAccount interface (implemented by CreditUnionCheckingAccount and CreditUnionSavingsAccount). [Not that one would trust real financial information to class-level security, of course--it's just an analogy]. – supercat Jan 17 '12 at 15:55
-
"An Interface is a contract with the public that you support those methods and properties" - I don't agree with this, I would say an interface is (or should be) a contract with the implementer. And I should be able to enforce the implementation of certain private methods and properties. – Gavin Williams Feb 08 '19 at 06:34
-
You would also need a big guy with a baseball bat to enforce me to implement *that* interface. I would just put a method stub to shut the compiler up, then put my actual implementation in another private method -- just out of spite, you know. – Ishmaeel Feb 08 '19 at 13:37
An interface is a contract that all implementing classes adhere to. This means that they must adhere to all of it or none of it.
If the interface is public then every part of that contact has to be public, otherwise it would mean one to friend/internal classes and a different thing to everything else.
Either use an abstract base class or (if possible and practical) an internal extension method on the interface.
-
If one were to declares a public abstract class, all of whose members and constructors were `internal`, then outside code could receive from the assembly references to things of that type, and pass such references back to the assembly's methods, while maintaining type safety throughout, without the outside code having to know anything about the class in question. Unfortunately, such an approach would only work if none of the concrete derivations of the abstract class would need to inherit from anything which doesn't derive from that abstract class. – supercat May 31 '13 at 23:55
-
An interface which contained internal members, if such a thing were allowed, would be much like the aforementioned abstract class, but with the advantage that it could be implemented by classes which were derived from classes that did not. – supercat May 31 '13 at 23:56
You can hide almost all of the code implemented by interfaces to external assemblies.
interface IVehicle
{
void Drive();
void Steer();
void UseHook();
}
abstract class Vehicle // :IVehicle // Try it and see!
{
/// <summary>
/// Consuming classes are not required to implement this method.
/// </summary>
protected virtual void Hook()
{
return;
}
}
class Car : Vehicle, IVehicle
{
protected override void Hook() // you must use keyword "override"
{
Console.WriteLine(" Car.Hook(): Uses abstracted method.");
}
#region IVehicle Members
public void Drive()
{
Console.WriteLine(" Car.Drive(): Uses a tires and a motor.");
}
public void Steer()
{
Console.WriteLine(" Car.Steer(): Uses a steering wheel.");
}
/// <summary>
/// This code is duplicated in implementing classes. Hmm.
/// </summary>
void IVehicle.UseHook()
{
this.Hook();
}
#endregion
}
class Airplane : Vehicle, IVehicle
{
protected override void Hook() // you must use keyword "override"
{
Console.WriteLine(" Airplane.Hook(): Uses abstracted method.");
}
#region IVehicle Members
public void Drive()
{
Console.WriteLine(" Airplane.Drive(): Uses wings and a motor.");
}
public void Steer()
{
Console.WriteLine(" Airplane.Steer(): Uses a control stick.");
}
/// <summary>
/// This code is duplicated in implementing classes. Hmm.
/// </summary>
void IVehicle.UseHook()
{
this.Hook();
}
#endregion
}
This will test the code.
class Program
{
static void Main(string[] args)
{
Car car = new Car();
IVehicle contract = (IVehicle)car;
UseContract(contract); // This line is identical...
Airplane airplane = new Airplane();
contract = (IVehicle)airplane;
UseContract(contract); // ...to the line above!
}
private static void UseContract(IVehicle contract)
{
// Try typing these 3 lines yourself, watch IDE behavior.
contract.Drive();
contract.Steer();
contract.UseHook();
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
}

- 5,734
- 3
- 34
- 43
Interfaces do not have access modifiers in their methods, leaving them open to whichever access modifier is appropriate. This has a purpose: it allows other types to infer what methods and properties are available for an object following an interface. Giving them protected/internal accessors defeats the purpose of an interface.
If you are adamant that you need to provide an access modifier for a method, either leave it out of the interface, or as you said, use an abstract class.

- 94,284
- 15
- 101
- 152
-
allowing other (read external) types to infer what method and properties are available for an object is a welcome choice? I would say the object should be able to decide what should be available for outside world to infer. – nawfal Sep 24 '12 at 11:13
-
Precisely, nawfal -- and an interface is a contract, not an object. Interfaces should be used to describe available behavior as opposed to the definition of an implementation detail. – Jon Limjap Sep 24 '12 at 17:11
-
Jon, today I realised its a contract. Not just a contract, but more like a "public specification for the whole world". I was questioning this principle, but when ppl put to words, they sound like "why are interface members public?" for which often found answers are flavours of "its a contract of that sort". [@Jon Skeet says here](http://stackoverflow.com/a/11162397/661933) that it is so, 'coz it is so. [Here](http://stackoverflow.com/a/7238707/661933) is another implication of having non public interface members. – nawfal Sep 24 '12 at 19:08
-
But now I am wondering why cant member definition in the interface itself be private, public etc. I to this date thought interfaces existed also to enforce a class design (which involves public, protected, private etc members) and still feel there should be something to enforce it. – nawfal Sep 24 '12 at 19:09
-
Late answer, but imagine private members in a public interface. How would a class be supposed to implement all members of an interface, if it couldn't even knew that they are there? Of course analogous to other modifiers. As noted in accepted answer, you can restrict access to interface itself, preventing any attempts to even implement the contract when you're not supposed to. So to speak, private/protected/internal interface would be like contract others don't know about. Interface with non-public members would be like unclear contract that might be impossible to fully implement. – user3613916 Jun 27 '14 at 10:37
I'm familiar with Java rather than C#, but why an earth would you want a private member within an interface? It couldn't have any implementation and would be invisible to implementing classes, so would be useless. Interfaces exist to specify behaviour. If you need default behaviour than use an abstract class.

- 113,588
- 46
- 195
- 237
-
1
-
I think it is possible to declare a whole interface (as opposed to an individual method) internal. That makes more sense. – Jon Limjap Sep 24 '12 at 17:12
-
1@JonLimjap it is possible, and the only good it does is, it hides the interface from external assemblies as expected, but they still requires its members be public (which is weird) which means those public properties and methods are visible to outside world!! – nawfal Sep 24 '12 at 18:51
In my opintion this violates encapsulation. I have to implement a methos as public then I implement an interface. I see no reason to force public in a class that impletements the interface. (c#)

- 548
- 7
- 19