C-Sharp protected internal access modifier

Hello friends,

In this 5 minute article, we will learn protected internal access modifiers with example.

protected internal means "protected OR internal". The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Step 1:   Create console application ConsoleApp2.

Step 2:   Add new ClassLibrary (.net framework) in same solution TestLibrary.

Step 3:   Add reference of TestLibrary2 in ConsoleApp2.

Step 4:   Add new class in TestLibrary project TestLibBaseClass and copy following code.

namespace TestLibrary2 { public class TestLibBaseClass { public int a; private int b; protected int c; protected internal int d; } public class Derivedclass : TestLibBaseClass { public System.Collections.Generic.List DerivedOfTestMethod() { System.Collections.Generic.List testlibvar = new System.Collections.Generic.List(); //Public Member testlibvar.Add(a); //Private Member Not Accessible //testlibvar.Add(b); //Protected testlibvar.Add(c); //internal Member testlibvar.Add(d); return testlibvar; } } }

Data Member 'b' of TestLibBaseClass in Derivedclass is not accessible due to private access modifier.

Step 5:   Add new class in ConsoleApp2 project DerivedFromTestBase and copy following code.

using TestLibrary; namespace ConsoleApp2 { public class DerivedFromTestBase : TestLibBaseClass { public System.Collections.Generic.List DerivedMethod() { System.Collections.Generic.List testlibvar = new System.Collections.Generic.List(); //Public Member testlibvar.Add(a); //Private Member Not Accessible //testlibvar.Add(b); //Protected testlibvar.Add(c); //protected internal testlibvar.Add(d); return testlibvar; } } class Program { static void Main() { TestLibBaseClass tb = new TestLibBaseClass(); DerivedFromTestBase d = new DerivedFromTestBase(); System.Console.WriteLine(d.i); System.Console.WriteLine(tb.a); } } }

In above code, DerivedFromTestBase private member 'b' is not accessible in another assembly.

while only public 'a' is accessible even every where outside assembly too.

private protected

The type or member can be accessed by code in the same class or in a derived class within the base class assembly.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories