What is the default access modifier for classes, methods, members, constructors, delegates and interfaces?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Simplest answer is the following.....
All members in C# always take the LEAST accessible modifier possible by default.
That is why all top level classes in an assembly are "internal" by default, which means they are public to the assembly they are in, but private or excluded from access to outside assemblies. The only other option for a top level class is public which is more accessible. For nested types its all private except for a few rare exceptions like members of enums and interfaces which can only be public. Some examples. In the case of top level classes and interfaces, the defaults are:
class Animal same as internal class Animal
interface Animal same as public interface Animal
In the case of nested classes and interfaces (inside types), the defaults are:
class Animal same as private class Animal
interface Animal same as private interface Animal
If you just assume the default is always the most private, then you do not need to use an accessors until you need to change the default. Easy.
Internal is the default modifier
Namespace level:
internal
Type level:
private
I would like to add some documentation link. Check out more detail here.
Short answer: minimum possible access (cf Jon Skeet's answer).
Long answer:
Non-nested types, enumeration and delegate accessibilities (may only have internal or public accessibility)
Nested type and member accessiblities
The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.
Note: CIL also has the provision for protected and internal (as opposed to the existing protected "or" internal), but to my knowledge this is not currently available for use in C#.
See:
http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx
(Man I love Microsoft URIs...)
Class is Internal by default.
Interface is Internal by default.
Interface members are public by default. (Interfaces won't allow us to specify any kind of accessibility to it's members.)
Note: If you try to specify any access specifier to interface's members then, it shows compile error.
Struct is Internal by default.