C# protected internal access modifier example

Protected internal is an access modifier often used in c# programming. and both of them can be used separately also; protected and internal.

public class Car
{
   protected internal int EngineNumber { get; set; }  
}

Protected means the class members can be accessed only by inheriting the class, not by creating a new instance, also not private to the class.

public class Car
{
    protected int EngineSize { get; set; }  
}

Internal means the class or members are accessible only within assembly.

public class Car
{
   internal int EngineType { get; set; } 
}

Now let’s try to access above property by creating few test methods in different classes (Maruti, Honda), we will experiment which are the property we can access.

public class Maruti : Car
{
    public void test()
    {
        int _engineNumber =this.EngineNumber;
        int _engineSize = this.EngineSize;
        int _engineType = this.EngineType;
    }
}


public class Honda 
{
    Car c = new Car();
    public void test()
    {
        int _engineNumber = c.EngineNumber;
        int _engineSize = 100; //EngineSize accessible  
        int _engineType = c.EngineType;
    }
}

As you can see in above example, in Honda class we cannot access EngineSize property, because the property is protected.

In above code internal members are accessible in both classes, Maruti and Honda, because all classes are in the same assembly, which means internal keyword will make no difference within same assembly class.

For example if we create an internal class in a project called “MyCompany”, the member will not be available to any other class outside the assembly, even after adding the assembly reference.

Now, let’s understand protected internal together.

public class Car
{
   protected internal int EngineNumber { get; set; }  
}

It means, the class members will be available to only inherited class and within the assembly only.

You may be interested in following tutorials

 
C# Protected Internal
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course