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
?
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 .
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.
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 .
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.
Protected methods can be called from derived classes. Private methods can't.
That's the one and only difference between private and protected methods.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With