1

The default access modifier for an interface is public. However, in C# can we ever use protected access modifier for an interface?

Joe
  • 145
  • 1
  • 9
  • Do you mean the members of the interface, or the interface itself? _Edited_ All declared members of an interface are always public. The accessibility of the interface itself can be `protected` if the interface is nested inside a non-static, non-sealed outer `class`. – Jeppe Stig Nielsen Sep 28 '15 at 12:17
  • as far as I remember, you can't specify a access modifier for the interface members. – Thangadurai Sep 28 '15 at 12:19
  • 1
    look into this: http://stackoverflow.com/questions/516148/why-cant-i-have-protected-interface-members – Anurag Jain Sep 28 '15 at 12:20
  • Sure, you can declare a nested interface protected. Why you'd ever do something like this is hard to guess. – Hans Passant Sep 28 '15 at 12:21

2 Answers2

4

In this example:

class C
{
  protected interface I
  {
  }
}

the nested type I is protected.

This means that I is visible to all of C and also to all classes that derive from C. For example this could be used to make protected instance methods inside C that contain I in their signatures or return types.

Note: The default accessibility for an interface is not public, like you claim. The default accessibility for a member of an interface is public. That is something else.

The default accessibility for the interface itself depends on what the interface itself is a member of. If the interface is a member of an "outer" class or struct (like my C above), it has the usual default accessibility of class and struct members, which is private. If the interface is a direct member of a namespace (possibly the global namespace), the default accessibility is the usual default for all non-nested types, which is internal.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
2

You can change this acceccibility.

See this page : https://msdn.microsoft.com/en-us/library/ms173121.aspx.

It's say that "Interfaces declared directly within a namespace can be declared as public or internal and, just like classes and structs, interfaces default to internal access."

Be carefull, as you see in this link https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx members are public by default and can't be modified.

Xaruth
  • 4,034
  • 3
  • 19
  • 26