Protected Access Modifier In C#

In this article I will explain Protected access modifier in C#.
  • 2658

Introduction

A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. It is the same as private but allows derived classes to access the member. Protected access specifier is used when we want to use the concept of inheritance in the program.

Accessibility

Cannot be accessed by object.
By derived classesExample.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

class Hello

{

    protected int x;

    protected int y;

}

class Hi : Hello

{

    public static void Main()

    {

       //Hello a = new Hello();

        // a.x = 10;

       // a.y = 15;

           Hi obj = new Hi();

      // Direct access to protected members:

        obj.x = 10;

        obj.y = 15;

        Console.WriteLine("x = {0}", obj.x);

        Console.WriteLine("y = {0}", obj.y);

        Console.ReadLine();

     }

}

 

In the following example if we can use the statement a.x =10,a.y= 15 then the program generates an error because Hello is not derived from Hi.

 

The output  of the following program


Clipboard121.jpg 

© 2019 DotNetHeaven. All rights reserved.