Access modifiers are keywords used in object-oriented programming to define how and where class members (fields, methods, properties, etc.) can be accessed. They are essential for implementing encapsulation and controlling visibility.
Common Access Modifiers in C#
1. public
Accessible from anywhere in the program. Used for methods or properties meant to be widely available.
2. private
Accessible only within the same class. Most restrictive and commonly used for data hiding.
3. protected
Accessible within the same class and its derived classes.
4. internal
Accessible anywhere within the same assembly/project.
5. protected internal
Accessible within the same assembly or in derived classes outside the assembly.
6. private protected
Accessible only within the same class or its derived classes in the same assembly.
Example in C#
public class Person
{
private string name; // Only inside this class
protected int age; // This class + derived classes
internal string address; // Same assembly
public string GetInfo() // Everywhere
{
return $"{name}, {age}, {address}";
}
}
Access modifiers help control data access, improve maintainability, and enhance security.
No comments:
Post a Comment