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?
763
02-Jul-2023
Updated on 04-Jul-2023
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
MyFieldfield is public, which means that it can be accessed from anywhere in the program. For example, the following code creates aMyClassobject and assigns the value 10 to theMyFieldfield:C#
The
MyClassclass can also be inherited from other classes. If a derived class inherits from theMyClassclass, it can access theMyFieldfield.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.