I have recently started learning C# language, which, compared to python, is a lot more verbose and structured. C# syntax is influenced by C and C++ languages.

Part of CS50 Introduction to Computer Science course used C language, so having seen the syntax before helps a lot. However, working mostly with Python, there is a lot of difference.

As I like to do, I will try to summarize key points as it helps me to learn and understand the language more.

Today I will take a look at Access Modifiers.

Access Modifiers

Access modifiers play a crucial role in determining the accessibility of classes, methods, and other members within your codebase.

They provide a means to control the visibility and accessibility of these elements, ensuring proper encapsulation and maintaining the integrity of your code.

Public Access Modifier

The public access modifier allows members to be accessed from any other code in the same assembly or referencing assembly.

1
2
3
4
5
6
7
public class MyClass
{
	public void MyMethod()
	{
		// Code
	}
}
Private Access Modifier

The private access modifier restricts access to members within the same class or struct. They cannot be accessed from outside the containing type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class MyClass
{

	private int myInteger;

	public void MyMethod()
	{
		// Code
	}
}
Protected Access Modifier

The protected access modifier allows access to members within the same class or derived classes. They cannot be accessed from outside the containing type or unrelated classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class MyBaseClass
{
    protected int myInteger;

    protected void MyMethod()
    {
        // Code
    }
}

public class MyDerivedClass : MyBaseClass // Inherit from Base Class
{
    public void AnotherMethod()
    {
        // Accessing protected member from base class
        myInteger = 10;
    }
}
Internal Access Modifier

The internal access modifier allows access to members within the same assembly but restricts access from outside the assembly.

1
2
3
4
5
6
7
8
internal class MyClass
{

	internal void MyMethod()
	{
		// Code
	}
}
Protected internal Access Modifier

The protected internal access modifier allows access to members within the same assembly or derived classes, whether they are in the same assembly or not.

1
2
3
4
5
6
7
8
9
public class MyBaseClass
{
    protected internal int myInteger;

    protected internal void MyMethod()
    {
        // Code
    }
}
Private protected Access Modifier

The private protected access modifier allows access to members within the same assembly and from derived classes that are in the same assembly.

1
2
3
4
5
6
7
8
9
public class MyBaseClass
{
    private protected int myInteger;

    private protected void MyMethod()
    {
        // Code
    }
}

Access modifiers play important role as they can greatly enhance the organization, security, and maintainability of your C# codebase.