0

I have the below type defined in one assembly.

public class TestAccessSpecifiers
    {
        public int Public { get; set; }
        protected int Protected { get; set; }
        private int Private { get; set; }
        public void SetValues()
        {
            Public = 10;
            Protected = 20;
            Private = 30;
        }
    }
    public class NewDerived : TestAccessSpecifiers
    {
        public void SetProtected()
        {
            Protected = 199;
        }
    }

In another type i am consuming this type and irrespective of whether I give protected or protected internal for the Protected Property, I am able to access it from this other program. Then what is the difference between setting both.

class Program
    {
        static void Main(string[] args)
        {
            TestAccessSpecifiers obj = new TestAccessSpecifiers();
            obj.SetValues();
            obj.Public = 100;

            Console.WriteLine(Convert.ToString(obj.Public));
            Console.ReadLine();

        }
    }
    class Derived : TestAccessSpecifiers
    {
        public void SetNewValues()
        {
            Public = 200;
            Protected = 500;
        }
    }
ckv
  • 10,539
  • 20
  • 100
  • 144

2 Answers2

3

From MSDN:

protected internal

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

protected internal grants both protected and internal access, it is less restrictive than either modifier alone.

Community
  • 1
  • 1
Preston Guillot
  • 6,493
  • 3
  • 30
  • 40
1

protected:

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal:

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

The source in MSDN here.

Note that on the CLR level, there is one more similar accessibility level, enabling greater flexibility whether access from the same assembly and derived classes is permitted:

  • FamilyAndAssembly — similar to protected internal from C#, but derived classes that are defined in another assembly cannot access such members; unfortunatelly, there's no equivalent in C#.
  • FamilyOrAssembly — corresponds to protected internal from C#.
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90