Curriculum
Access modifiers in C# are keywords that define the level of access that a member (field, property, method, etc.) has from other parts of the program. There are five access modifiers in C#:
public class MyClass
{
public int MyPublicField; // can be accessed from any code
}
public class MyClass
{
private int MyPrivateField; // can only be accessed within this class
public void SomeMethod()
{
// can access MyPrivateField here
}
}
public class MyBaseClass
{
protected int MyProtectedField; // can be accessed within this class or any derived class
}
public class MyDerivedClass : MyBaseClass
{
public void SomeMethod()
{
MyProtectedField = 10; // can access MyProtectedField here
}
}
internal class MyClass
{
internal int MyInternalField; // can be accessed within this assembly
}
public class MyBaseClass
{
protected internal int MyProtectedInternalField; // can be accessed within this assembly or any derived class
}
public class MyDerivedClass : MyBaseClass
{
public void SomeMethod()
{
MyProtectedInternalField = 10; // can access MyProtectedInternalField here
}
}
Access Modifier Rules:
Overall, access modifiers are an important feature of C# that help developers to control the visibility and accessibility of members in their code. By understanding the rules of access modifiers, developers can write more secure and maintainable code.