Introduction:

  • In this article we will explain how to use Protected Access modifier in c# or What is Protected Access modifier or why use Protected Access modifier in c# with example.

  • Description:

 

Protected Access modifiers or specifiers is a keywords in c#. The Protected methods and variables accessible within its class and by derived class instances. In other words protected access specifier hides its member variables and methods from other classes and objects. This type of variable or method can only be accessible in within its class and child class. It becomes very important while implementing inheritance.  

  • Example of C# Protected Access Specifier

Let's take an example to demonstrate C# Protected Access modifier

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace AccessSpecifiers
{
    class User
    {               protected string designation = "Software Developer";
        protected void GetUser()
        {
            Console.WriteLine("Name : Aditya Kumar Patel");
        }
    } 
    class Program
    {
        static void Main(string[] args)
        {
            User User = new User();
            //Accessing protected function 
            User.GetUser(); //Compile Time Error
            //Accessing protected variable 
            Console.WriteLine("Designation :" + User.designation);//Compile Time Error
            Console.ReadLine();
        }
    }
}

 

Output:


In this example, we have created two classes User and Program . User class contains protected

variables and protected method. We are accessing these protected members from outside the class,

so there is compile time error.

 

  • Example of C# Protected Access Specifier with inheritance

Let's take an example to demonstrate C# Protected Access modifier with inheritance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace AccessSpecifiers
{
    class User
    {               protected string designation = "Software Developer";
        protected void GetUser()
        {
            Console.WriteLine("Name : Aditya Kumar Patel");
        }
    }
    class Program : User
    {
        static void Main(string[] args)
        {
            Program program = new Program(); 
            //Accessing protected function 
            program.GetUser();
            //Accessing protected variable 
            Console.WriteLine("Designation :" + program.designation);
            Console.ReadLine();
        }
    }
}

OutPut:


Here, we are accessing protected members within child class by using inheritance.


I hope this article will help to you.



0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.