Sunday, March 29, 2009

C# .NET Default Access Modifiers

It's good to refresh what the default access modifiers are in C#. Default access modifiers could explain why you can't see something you declared when expect to see it and vice versa.

First let's quickly review all the access modifiers in C#.
private: Can be accessed by members of the same class only.
protected: Can be accessed by members of the same class plus members of derived classes only.
internal: Can be accessed by all that is in the same assembly regardless of what class they are in. But can only be accessed from the same assembly.
public: Can be accessed by everything.

The general rule is that the default access modifier is as secured as possible for the declaration context. This does not mean that everything is private by default because private does not make sense for everything. So here is the breakdown.

Data types: class, struct, enum
For data types such as classes the most strict reasonable access modifier is internal. And that is exactly the default modifier. So when declaring a new class it is internal by default so that it can be accessed by other classes in the same assembly. It does not make sense for a class to be private by default because it would inaccessible.

Members: variables, methods
For member variables and methods which are inside a certain data type from the list above, the most restrictive reasonable modifier is private and that is it. Any time a member is declared with no access modifier, it is private by default.

No comments: