23

I want to know what is the meaning of protected in C#, why we use it, and the benefit of the keyword?

For instance

protected int currentColorIndex;

Please elaborate.

Nishant Kumar
  • 5,995
  • 19
  • 69
  • 95
  • 6
    Just feels like it *must* be a duplicate, but I can't find exactly the same question elsewhere on SO. – serg10 Sep 02 '10 at 11:48
  • 1
    Now that you have the basics down from these answers, you might want to delve into some of the many subtleties. See http://blogs.msdn.com/b/ericlippert/archive/tags/protected/ for some of them. – Eric Lippert Sep 02 '10 at 14:27
  • related: http://stackoverflow.com/questions/3500298/what-is-the-difference-between-access-specifier-protected-and-internal-protected –  Sep 02 '10 at 17:16

7 Answers7

47

Everyone's answer is similar (a definition and/or a excerpt/link to MSDN), so ill attempt to answer your original 3 questions:

The Meaning:

Any field marked with 'protected' means it is only visible to itself and any children (classes that inherit from it). You will notice in the ASP.NET Web Forms code behind model, event handlers (such as Page_Load) are marked 'protected'. This is because the ASPX Markup file actually inherits from the code-behind file (look at the @Page directive to prove this).

Why We Use It:

The common use of the protected accessibility modifier is to give children access to it's parents properties. You might have a base class for which many subclasses derive from. This base class may have a common property. This is a good case for a protected property - to facilitate the re-use and central maintenance of common logic.

The Benefit:

Kind of similar question to "why we use it?" But essentially it gives coarse-grained control over properties. You can't just think of "when you use protected". It's more a case of choosing when to use which accessibility modifier (private, public, internal, protected). So the benefit is really the same benefit of any accessibility modifier - provide a robust and consistent object model, maximising code re-use and minimizing security risks associated with incorrectly exposed code.

Hope that helps.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Is it possible to access a protected method inside an abstract class or do we need to override it? For example, I have a class named "Dad" which has a `protected void WalkingAndRunning()` method. The "Dad" class is inherited by "Son" class. Is it possible to use the `protected void WalkingAndRunning()` method there? Just curious. – Musikero31 Dec 02 '11 at 07:10
  • 1
    @Musikero31 The dad protected function is automatically inherited in Class Son : Dad.. no need to even list it in Son Class, unless U want to change what it does. – Joseph Poirier Apr 17 '19 at 21:21
  • 1
    @JosephPoirier So after 8 years and looking at my question and you answering my question in almost the same way as how I will answer it makes me smile as I look back to how I was before and how I was now. I'll upvote your answer – Musikero31 Apr 18 '19 at 02:15
24

As others have already pointed out:

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.

Here is a small example:

public class A
{
    protected string SomeString;
    public string SomeOtherString;
}

public class B : A
{
    public string Wrapped
    {
        get { return this.SomeString; }
    }
}

...

var a = new A();
var s = a.SomeOtherString; // valid
var s2 = a.SomeString; // Error

var b = new B();
var s3 = b.Wrapped; // valid
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • Thanks for this. Can you clarify whether `b.SomeString` is valid or not? This is the part that is not explained on MSDN. – David Tang Apr 12 '11 at 02:11
  • 2
    @Box9, `b.SomeString` is not valid because it is `protected`. `protected` basically just means `private` but with the exception that inheriting classes may access it (as a `private` variable). – Klaus Byskov Pedersen Apr 14 '11 at 17:43
  • @Klaus, thanks that makes sense. I only asked because the example [on MSDN](http://msdn.microsoft.com/en-us/library/bcd5672a(v=vs.71).aspx) don't really illustrate this as the code is within a static method of `B`. – David Tang Apr 14 '11 at 22:21
12

"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."

see

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected

phuzi
  • 12,078
  • 3
  • 26
  • 50
Andreas Paulsson
  • 7,745
  • 3
  • 25
  • 31
  • 9
    −1: Doesn’t answer the question “why we use it”. – Timwi Sep 02 '10 at 11:54
  • but sir instead of declaring protected we can also use as private acording to your answer . – Nishant Kumar Sep 02 '10 at 12:11
  • 4
    @Nishant - not so: 'private' constrains the members to be used only by this class, and not visible to any other class. – Steve Townsend Sep 02 '10 at 14:34
  • @Nishant - That is correct, I should have stated the difference between protected and private (which @Steve Townsend did). protected hide the ,e,eber from clients but still makes it visible to subclasses. – Andreas Paulsson Sep 03 '10 at 06:18
7

Straight from the MSDN:

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.

Source

Using protected means you can have functionality in a class that's available to derived classes, but not to classes that just instantiate the object.

This page compares the different access modifiers and explains what they mean and gives a table of the default modifiers for different objects (enum, class, interface and struct).

ChrisF
  • 134,786
  • 31
  • 255
  • 325
6

Definition provided in another answer. Why is this good? You don't have to duplicate data/code from base class to its derived classes when protected offers them access to base class implementations, without the unwanted exposure to unrestricted external usage that would be implied by public.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
3

It means that the field is only visible to the class itself and inherited classes.

Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
3

Think of it like this. A class presents three interfaces:

  1. Towards itself, with full access to internal implementation details (public, protected, private methods and attributes). By definition, anything you do in a class may affect anything else.
  2. Towards its clients, with access only to the public methods and attributes. You minimize the public interface of a class in order to minimize unexpected consequences of changes: the less code knows about your internals, the more freely you can modify them later.
  3. Towards its descendants, with access to the public and the protected methods and attributes. Whatever you do to protected and public methods will impact not only clients, but also descendants that modify the base functionality of your class. OO is about reducing coupling and increasing cohesion: there is no stronger coupling between classes than the inheritance relation (well, apart from the C++ friend, of course)!

The third interface is the hardest general design challenge in OO: what can reasonably be overridden (virtual methods and properties), and in order to override, what other functionality is needed (plain protected methods and attributes)? Because this is such a challenge, having classes sealed by default is actually a good idea, counterintuitive as it frequently seems to OO beginners, to whom it seems like an unnecessary handicap.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51