C# Tutorial - 14 - Access Levels


Uploaded by ProgrammingVideos on 14.01.2010

Transcript:
There are five access levels available in C#. These are public, protected, internal,
protected internal, and private. To show their differences let's define one field for each
access level. The default access level for fields and methods are private, so writing
private here is optional.
In our first test we can see that all members regardless of access levels are accessible
in the class where they are declared. This is the only place where the private member
can be accessed. A protected member can also be accessed in a derived class, but it fails
when trying to access the member from outside of the class.
The internal member can be accessed anywhere within this program, but not from another
assembly. To demonstrate this we'll set the base class to public and add an empty Main
method since this program is set to become an executable. We can now compile the class
into a publically available assembly. Next, we'll open up the solution explorer and right
click on the solution to add new project. Create a console application the same as before.
We then need to add a new reference to this project by right clicking on references. Choose
the Projects tab and import the first project's assembly. We now gain access to our public
class from this program. To help distinguish between the code files we'll go ahead and
give this one a new name.
If we now try to access the members from here we find that both the internal and protected
internal members have become inaccessible because we're outside of the assembly where
they are declared. Since protected internal access means either protected or internal
we can make that member accessible here from inside of a class deriving from the Base class
of our first project. The last access level is public, which gives unrestricted access
from anywhere we can reach the member.
Now let's return to our main project to look at class access levels. To be able to see
this class from the other assembly we had to mark it as public. By default the class
is made internal, and these two are the only access levels allowed to a top-level class.
Classes can also contain inner classes, which can be set to either one of the five access
modifiers. These access levels have the same effect to inner classes as they do to other
members. If the class is inaccessible it cannot be instantiated or inherited. By default their
access level is private, so they can only be used within the class where they're defined.