Accessibility levels

* public, private, protected, internal this are called by access modifier. Only one access modifier is allowed for a member or type, except when you use the protected internal or private protected combinations(private protected is available since C# 7.2).

public : Access is not restricted.

private : Access is limited to contained type.

protected : Access is to the containing class or type derived from the containing class


* Difference between private and protected : Private type can't access at class or type derived from the containing class. So Private's level of limit is more higher than protected.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class testDevice
{
    private string name = "hi";    
}
 
 
public class testDeviceMobileRobot : testDevice
{
    public void changing(string msg)
    {
        base.name = msg;    // CS0122. 보호수준 때문에 testDevice.name에 접근할 수 없습니다.
    }
}




1
2
3
4
5
6
7
8
9
10
11
12
13
public class testDevice
{
    protected string name = "hi";    
}
 
 
public class testDeviceMobileRobot : testDevice
{
    public void changing(string msg)
    {
        base.name = msg;    // Ok.
    }
}




internal : Access is limited to the current assembly. Internal type or members are accessible only within files in the same assembly, as in this example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Assembly1.cs  
// Compile with: /target:library  
internal class BaseClass
{
    public static int intM = 0;
}
 
// Assembly1_a.cs  
// Compile with: /reference:Assembly1.dll  
class TestAccess
{
    static void Main()
    {
        BaseClass myBase = new BaseClass();   // CS0122  
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Assembly2.cs  
// Compile with: /target:library  
public class BaseClass
{
    internal static int intM = 0;
}
 
// Assembly2_a.cs  
// Compile with: /reference:Assembly2.dll  
public class TestAccess
{
    static void Main()
    {
        BaseClass myBase = new BaseClass();   // Ok.  
        BaseClass.intM = 444;    // CS0117  
    }
}
cs


Posted by 나무길 :