Junior — Middle
Could you explain what access modifiers are and how they are used in programming?
sobes.tech AI
Answer from AI
Access modifiers are keywords in programming languages that define the visibility and accessibility level of class members (fields, methods) to other parts of the program.
In C#, the main access modifiers are:
- public — accessible to everyone, the member is available from anywhere.
- private — accessible only within the class itself.
- protected — accessible within the class and its subclasses.
- internal — accessible within the current assembly.
- protected internal — accessible within the current assembly and from subclasses.
Example of usage:
class Person
{
private string name; // accessible only within Person
public int Age { get; set; } // accessible publicly
protected void DisplayInfo()
{
Console.WriteLine($"Name: {name}, Age: {Age}");
}
}
Access modifiers help encapsulate data and control interaction between program components.