Table of Contents
Protected Modifiers in C#
Examples to Implement Protected in C#
Example #1 – Without Implementing Child Class
Example #2 – Implementing with Inheritance
Example #3
Protected Internal Access Modifier
Importance of Protected in C#
Conclusion

Protected in C#

Sep 03, 2024 pm 03:28 PM
c# c# tutorial

In this article, we will see how protected in c# can be implemented in detail. With the help of access modifiers we can restrict the accessibility level of parameters and classes. There are following access modifiers in C#

  • Public
  • Private
  • Protected
  • Internal

Protected Modifiers in C#

In c#, we can use the protected modifier to specify that the access is limited to the containing type. Also, we can use it for the types derived from the containing class. The word protected means it can be accessible or visible to itself and also to the derived classes.

With the help of this member or type only be accessed by code which is used in the same class or which is used in the derived class. The keyword protected is between the private and public modifiers. It is almost the same as a private modifier but it allows the member to access the derived classes. We mostly use the protected keyword when we want to give access to children’s properties to their parents. So we can reuse the logic with the help of protected keyword.

Example:

using System;
class Test
{
protected int _x; private int _y;
}
class Test1 : Test
{
public Test1 ()
{
// In this we can  access the variable protected int but we cannot access private int variable
Console.WriteLine(this._x);
}
}
class Program
{
static void Main()
{ Test1 b = new Test1 (); }
}
Copy after login

Consider 2 classes, Test and Test1. Class Test1 is derived from Test. If we look inside the class Test, we can see two int field has been declared. 1 protected and 1 private.

In class B Test1 we can access the protected int, but we cannot access the private int. So the protected modifier gives us additional access in the derived class. So with the help of protected keyword, we can access the protected fields includes all the derived classes.

A class can also be protected. Below is the example of how to declare it

Syntax:

public class Test
{
protected class Child
{
}
}
Copy after login

Only in nested class, we can declare the class as protected. We cannot define it inside a namespace.

Examples to Implement Protected in C#

Below are the examples to show how we can implement protected in C#:

Example #1 – Without Implementing Child Class

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class demo
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\name is " + name);
}
}
class Program
{
static void Main(string[] args)     // main method
{
demo d = new demo();
Console.Write("Enter your name:\t");
d.name = Console.ReadLine();
d.print();
Console.ReadLine();
}
}
}
Copy after login

In the above example, the string is declared as protected. This program will raise an error because protected will hide its members from other classes. So it will only accessible in child class.

Example #2 – Implementing with Inheritance

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Demo
{
protected string name = "Protected Keyword";
protected void Display(string val)
{
Console.WriteLine("This is " + val);
}
}
class Program : Demo   // inheritance
{
static void Main(string[] args)
{
Program program = new Program();
// Accessing protected variable
Console.WriteLine("This is " + program.name);
// Accessing protected function
program.Display("protected example");
Console.ReadLine();
}
}
}
Copy after login

In the above example, Parent class consists of protected members. Protected is used to declare the string. Now child class is derived from a parent class and the concept of inheritance is used to access the protected members.

Output:

Protected in C#

Example #3

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Parent
{
private String Private = "My name is John";    // string declared as private
protected String Protected = "My name is Dan"; //  string declared as protected
}
class Child : Parent // inheritance
{
public void Show()
{
Console.WriteLine(Protected);
}
}
class Program
{
static int Main(string[] args)  // main method
{
Child child = new Child();    // child object
child.Show();
Console.ReadKey();
return 0;
}
}
}
Copy after login

In the above example, the parent class contains private and protected strings. The child class is derived from the parent class. Show() can’t access private though but it can access protected. A child class object is used to call the method. Protected is used to protect the members from being accessed outside of class.

Output:

Protected in C#

We can also declare the constructor as protected. So by declaring any constructor as protected, we can call it from a subclass.

Syntax:

public class TEst : Test1
{
public Test() : base() // here we can Call the protected base constructor
{
}
}
Copy after login

We cannot call a protected method. We can call the protected constructor from the derived class.

Protected Internal Access Modifier

With the help of protected internal, we can specify that the access is limited to current types that are derived from the containing classes. So this makes insure that the member and type can be accessed by code in the same class or by the derived class which is written in another assembly.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Demo
{
protected internal string name;    // variable is declared as protected internal
public void print()
{
Console.WriteLine("name is " + name);
}
}
class Program
{
static void Main(string[] args) // main method
{
Demo d = new Demo();
Console.Write("Enter your name:\t");
// Accepting value in protected internal variable
d.name = Console.ReadLine();
d.print();
Console.ReadLine();
}
}
}
Copy after login

Output:

Protected in C#

Importance of Protected in C#

Protected keyword is useful because this type of variable can be accessed by the code which is used in the same class. It is useful when we want to give authority to child class so that it can access parent class members. So in that sense, it is important in achieving code reusability.

Conclusion

So we can use protected with variables and access them using the inheritance concept. It can be used where members can be accessed by the class itself or subclass.

The above is the detailed content of Protected in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

See all articles