Blog

Filter posts by Category Or Tag of the Blog section!

Private protected in C# 7.2

Thursday, 06 July 2017

If you remember protected internal which was introduced in earlier versions of C#, it can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly. For example, if you look at the following code:

 

namespace namespace1

{

    public class BaseClass1

    {

        protected internal void ProtectedInternalMethod()

        {

 

        }

    }

}

 

namespace namespace2

{

    public class BaseClass2 : BaseClass1

    {

        public void Method1()

        {

            ProtectedInternalMethod();

        }

    }

 

    public class BaseClass3

    {

        public void Method2()

        {

            var baseClass1 = new BaseClass1();

            baseClass1.ProtectedInternalMethod();

        }

    }

}

 

We defined a method in BaseClass1 as protected internal and we used that method in other classes named BaseClass2 and BaseClass3. Notice that BaseClass2 is deriving from BaseClass1 But and BaseClass3 Does NOT but we can use ProtectedInternalMethod() in both of them.

Now look at the following example:

 

namespace namespace3

{

    public class BaseClass4

    {

        private protected void PrivateProtectedMethod()

        {

 

        }

    }

}

 

namespace namespace4

{

    public class BaseClass5 : BaseClass4

    {

        public void Method2()

        {

            PrivateProtectedMethod();

        }

    }

 

    public class BaseClass6

    {

        public void Method1()

        {

            var BaseClass4 = new BaseClass4();

            BaseClass4.PrivateProtectedMethod(); //it's compile error! We don't have access to private protected method here

        }

    }

}

 

 

We used the same structure but with a private protected access modifier. If you consider the above samples, you will find out the Protected internal is so-called protected OR internal so it's accessible in the same assembly or the derived class(even in another assembly) whereas the private protected is Protected AND internal, so it's accessible in the same assembly AND derived classes! 

Category: Software

Tags: C#

comments powered by Disqus