What are the access modifiers in C# and how do they control the visibility of class members?
What are the access modifiers in C# and how do they control the visibility of class members?
41402-Jul-2023
Updated on 04-Jul-2023
Home / DeveloperSection / Forums / What are the access modifiers in C# and how do they control the visibility of class members?
What are the access modifiers in C# and how do they control the visibility of class members?
Aryan Kumar
04-Jul-2023In C#, access modifiers are keywords that control the visibility of class members. They can be used to restrict access to class members, such as fields, properties, methods, and events.
There are five access modifiers in C#:
The default access modifier for class members is
private
. This means that class members are only accessible from within the class. To make a class member accessible from outside the class, you can use one of the other access modifiers.For example, the following code defines a class with a public field:
C#
The
MyField
field is public, which means that it can be accessed from anywhere in the program. For example, the following code creates aMyClass
object and assigns the value 10 to theMyField
field:C#
The
MyClass
class can also be inherited from other classes. If a derived class inherits from theMyClass
class, it can access theMyField
field.Access modifiers can be used to control the visibility of class members and to protect sensitive data. By using access modifiers, you can make your code more secure and reusable.