What is Protected Access Modifier in C#?

Only the members of a class can be marked with protected access modifier.



When you mark a member to be protected, then it will be accessible within the class and all the derived classes of this class. Consider the following example:

public class sampleClass {
protected int member1;
}
public class derivedClass:sampleClass {
public void setMember1(int data) {
member1 = data;
}
}

In this example, protected member called member1 of sampleClass is accessed directly inside derivedClass which inherits from sampleClass. This is acceptable because protected members will be visible in derived classes of sampleClass.

Consider the following code below:

public class testClass {
public static void Main() {
sampleClass obj = new sampleClass();
obj.member1 = 10;
}
}

Here you access the protected member inside a class that is not derived from sampleClass. Hence you will end up in the following error:

“‘sampleClass.member1’ is inaccessible due to protection level”

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.