Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"protected" methods in C#?

Tags:

What are the benefits to defining methods as protected in C#?

like :

protected void KeyDemo_KeyPress( object sender, KeyPressEventArgs e )  {     // some code } 

As compared to something like this:

private void FormName_Click( object sender, EventArgs e ) {     //some code } 

I've seen such examples in many books and I don't understand why and when do they use private vs protected?

like image 773
Sherif Avatar asked May 30 '09 17:05

Sherif


People also ask

What is a protected method?

A protected method is like a private method in that it can only be invoked from within the implementation of a class or its subclasses. It differs from a private method in that it may be explicitly invoked on any instance of the class, and it is not restricted to implicit invocation on self .

What is a protected method in C#?

C# Protected: Using the Protected Keyword in C# public means that your object's method can be called from anywhere, or that the instance variable that you declare public can be accessed from anywhere, whether outside or inside the class itself.

What is protected vs private?

private: The type or member can be accessed only by code in the same class or struct . protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class .

How can use protected method from another class in C#?

The method is overrided one of the derived classes: public class Derived1 : BaseClass { protected override void Foo() { //some code... } } Another derived class has an instance of the first derived class.


2 Answers

Protected methods can be called from derived classes. Private methods can't.

That's the one and only difference between private and protected methods.

like image 158
Philippe Leybaert Avatar answered Oct 24 '22 10:10

Philippe Leybaert


Often 'protected' is used when you want to have a child class override an otherwise 'private' method.

public class Base {     public void Api() {        InternalUtilityMethod();     }     protected virtual void InternalUtilityMethod() {        Console.WriteLine("do Base work");     } }  public class Derived : Base {     protected override void InternalUtilityMethod() {        Console.WriteLine("do Derived work");     }  } 

So we have the override behavior we know and love from inheritance, without unnecessarily exposing the InternalUtilityMethod to anyone outside our classes.

var b = new Base(); b.Api();  // returns "do Base work" var d = new Derived(); d.Api(); // returns "do Derived work" 
like image 25
Bruce Avatar answered Oct 24 '22 12:10

Bruce