Access Modifiers in C#
Access Modifiers / Specifiers:
C# Access modifiers or specifiers are
the keywords that are used to specify accessibility or scope of types
(Class, interfaces, variables,
properties and methods etc.)
in the C# application.
It is used when you don’t want other
programs to see the properties or methods of a class.
Access modifiers restrict access so
that other programs cannot see the properties or methods of a class.
Access specifier is just to control the
visibility of a member.
In C#, there are 5 basic types of
access modifiers.
1.
public
2.
private
3.
protected
4.
internal
5.
protected internal
1. Public:
When we declare a type or type member
public, it can be accessed from anywhere.
There are no restrictions on accessing
public members.
This access modifier has the most
permissive access level in comparison to all other access modifiers.
Syntax:
public TypeName
TypeName - class, properties, methods,
interfaces, variables etc.
2. Private:
When we declare a type member with the
private access modifier, it can only be accessed within the same class or
struct.
Any other class inside the current or
another assembly is not granted access to these members.
Private access is the least permissive
access level.
Syntax:
private TypeName
3. Protected:
When we declare a type member as
protected, it can only be accessed from the same class and its derived classes.
It means a class which is the subclass
of the containing class anywhere in the program can access the protected
members.
A protected member of a base class is
accessible in a derived class only if the access takes place through the
derived class type.
Syntax:
protected TypeName
4. Internal:
When we declare a type or type member as
internal, it can be accessed only within the same assembly.
Internal members are accessible only
within files in the same assembly (.dll).
Access is limited to only the current
Assembly, that is any class or type declared as internal is accessible anywhere
inside the same namespace. It is the default access modifier in C#.
Syntax:
internal TypeName
5. protected internal:
the protected internal is a combination of
protected and internal access modifiers.
When we declare a member protected internal, it can
be accessed from the same assembly and the derived class of the containing
class from any other assembly.
The protected internal accessibility means
protected OR internal, not protected AND internal.
Syntax:
protected
internal TypeName.
Real Life Examples:
Example1:
i)
Owner à
public.
ii)
Company 1 and Company 2 à
internal
iii)
Departments à
private
iv)
Manager à
Protected
Example2:
The moon - any one can see and any
one can talk about it --public
Television - only person at home can
watch, but outsiders can't. - internal
Bike - any person at home can
ride, and if necessary child can take it out of hometown. - protected.
Chequebook - only I can use - private.
Comments
Post a Comment