Access Specifiers
These are also modifiers used to define scope of a type (Class
or Interface or Structure) as well as their members i.e. who can access them
and who cannot.
C# has 5 different Specifiers those are
- Private
- Internal
- Protected
- Protected Internal
- Public
Note – Members define in a type with any
Specifiers (Scope) are always accessible within the type, all the restrictions
comes in to the picture only when we try to access them outside of the type.
. Private
Members declared as private under
class or structure is not accessible outside of them in which they are
defining. Default scope for members of a class and structure is private, but
public in the case of interface. Interface cannot contain private member in it.
A type can never be declared as private.
Protected –
Members declared as protected under a
class or interface can be accessed only from its children or within itself , an
non – child class cannot consumed .Types cannot be declared as protected also.
Q – How to restrict a class not to be accessible from any other
class?
Ans – This can be done by declaring
constructors of classes private
Q – How to restrict a class not to be inherited for any other
class?
Ans – This can be done by declaring
class as Sealed.
Q – How to restrict a class not to be accessible for any other
class to consume by creating its object?
Ans – This can be done by declaring
constructor of a class is Private.
. Internal
Members of types that are declared as
internal are accessible only within the project both from child or non-child
class the default Scope for only type in C# is internal only.
Protected internal
Members declared as Protected Internal
enjoy dual scope i.e. within the project they behave as Internal providing
access to others, outside the project they change protect and still provide
access to child classes.
Public –
A type or member of a type if declared as Public is
global in scope that can be access from anywhere.
Cases
|
Private
|
Internal
|
Protected
|
Protected Internal
|
Public
|
case 1
|
|
|
|
|
|
case 2
|
X
|
|
|
|
|
case 3
|
X
|
|
X
|
|
|
case 4
|
X
|
X
|
|
|
|
case 5
|
X
|
X
|
X
|
X
|
|
Case 1 –
Accessing members with in the same class.
Case 2 - Accessing members with in child class of same
project.
Case 3 -
Accessing members with in non-child class of same project
Case 4 -
Accessing members with in child class of other project.
Case 5 -
Accessing members with in non-child class of other project.
0 Comments