Article
Object Oriented C# for ASP.NET Developers
Access Modifiers
As we have already seen, classes should usually be set public to allow code elsewhere in your application to make use of it. But there are times when you'll want to restrict access to a class; for example, you might only want to allow other classes in the same assembly (DLL file) to use it. That's when you'll want to specify a different access modifier. Class members, which include fields and methods, can be similarly modified to control access to them.
Here are the access modifiers supported by C#:
public: any code may access the class or class member.private: the class or class member is not accessible outside of the class that contains it (yes, in advanced cases, you can put a class inside another class).protected: the class or class member is only accessible by the class that contains it, or any subclass of that class.internal: the class or class member is only accessible by code in the same assembly (DLL).protected internal: the class or class member is accessible by code in the same assembly (DLL), or by any subclass of the class that contains it.
If you don't specify any access modifier, C# will default to private.
Consider the following sample declarations:
int numNuts = 0;
bool PickNut(int numberToPick) {
...
}
Since no access modifiers are specified, both of these members will act as if they were declared private. Even if the class is declared public, the value of the above numNuts field (assuming it is declared as the field of the class) may only be accessed or modified by code inside the same class. Similarly, the PickNut method shown above may only be invoked by code elsewhere in the class.
Distinguishing the situations in which each access control setting is appropriate takes a little experience. It's tempting at first to just declare everything public to save yourself the trouble of worrying when something is accessible and when it isn't. While this will certainly work, it is definitely not in the spirit of object oriented programming. Code that you plan to reuse or distribute, especially, will benefit from being assigned the most restrictive access control settings that are appropriate. One reason for this is illustrated in the following section.
For now, just take note of the choices I make for access modifiers. I'll explain my reasons in each case, and before long you'll be able to choose your own!