In 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.
Public: Public members are accessible from anywhere in the program.
Protected: Protected members are accessible from within the class and from derived classes.
Internal: Internal members are accessible from within the assembly.
Private: Private members are only accessible from within the class.
Protected internal: Protected internal members are accessible from within the class, from derived classes, and from other classes in the same assembly.
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#
public class MyClass
{
public int MyField;
}
The MyField field is public, which means that it can be accessed from anywhere in the program. For example, the following code creates a
MyClass object and assigns the value 10 to the MyField field:
C#
MyClass myClass = new MyClass();
myClass.MyField = 10;
The MyClass class can also be inherited from other classes. If a derived class inherits from the
MyClass class, it can access the MyField 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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In 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.