Protected Access Specifiers C#

In this chapter you will learn:
  • What is protected access specifier?
  • What is the boundary of protected access specifier?
  • How to use protected access specifier in C# programming?

The protected access specifier hides its member variables and functions from other classes and objects. This type of variable or function can only be accessed in child class. It becomes very important while implementing inheritance.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Protected_Specifier
{
    class access
    {
        // String Variable declared as protected
        protected string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            access ac = new access();
            Console.Write("Enter your name:\t");
            // raise error because of its protection level
            ac.name = Console.ReadLine();
            ac.print();
            Console.ReadLine();
        }
    }
}

 

Output

'Protected_Specifier.access.name' is inaccessible due to its protection level.
This is because; the protected member can only be accessed within its child class. You can use protected access specifiers as follow: __
protected access-specifiers

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Protected_Specifier
{
    class access
    {
        // String Variable declared as protected
        protected string name;
        public void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }
    }

    class Program : access // Inherit access class
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.Write("Enter your name:\t");
            p.name = Console.ReadLine(); // No Error!!
            p.print();
            Console.ReadLine();
        }
    }
}

Output


Enter your name:     Steven Clark
My name is Steven Clark
__

Summary

In this chapter you learned about protected access specifier. You also learned its boundary and scope and implementation in a program. In next chapter you will learn about internal access specifier in C#.

 

Share your thought