Access
Modifiers are used to control the visibility of a type (classes,
interfaces, structures, enumerations, and delegates) or their members
(properties, methods, constructors, and fields) to other parts of an
application.
Role
of each access modifier and where it may be applied:
Access Modifier | Applicable to | Description |
---|---|---|
public | Types or type members | Public items have no access restrictions. A public member can be accessed from an object, as well as any derived class. It can also be accessed from other external assemblies. |
private | Type members or nested types | Private items can only be accessed by the class (or structure) that defines the item. |
protected | Type members or nested types | Protected items can be used by the class which defines it, and any child class. However, protected items cannot be accessed from the outside world using the C# dot operator. |
internal | Type or type members | Internal items are accessible only within the current assembly. Therefore, if you define a set of internal types within a .NET class library, other assemblies are not able to make use of them. |
protected internal | Type members or nested types |
When
the protected and internal keywords
are combined on an item, the item is accessible within the
defining assembly, the defining class, and by derived classes.
|
Note:
By default, type members (ex. members of a class) are
implicitly private
while types (ex. classes) are
implicitly internal.
//
An internal class with a private default constructor.
class
Country
{
//
default constructor – implicitly private
Country()
{
}
}
Note:
Nested types can have private access, but non-nested types cannot be
marked private.
public
class Country
{
//
OK! Nested types can be marked private.
private
enum FlagColor
{
Red,
Green, Blue
}
}
Here,
it is permissible to apply the private
access modifier on the
nested type. However, non-nested types (such as the Country)
can only be defined with the public
or internal modifiers.
//
Error! Nonnested types cannot be marked private!
private
class Country
{}
No comments:
Post a Comment