"protected" methods in C#?
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"
- Protected methods can be accessed by inheriting classes where as private methods cannot.
- Keeping in mind that .aspx and .ascx file inherit from their code behind classes (default.aspx.cs), the protected methods can be accessed from within the .aspx/.ascx
Keep this in mind too: If you have a button and that button's OnClick is set to Button_Click
<asp:Button id="btn" runat="server" OnClick="Button_Click" />
then the Button_Click method needs to have at least protected visibility to be accessible by the button.
You could get around this by added the following to you Page_Load method:
btn.Click += new EventHandler(Button_Click);
Protected methods can be called from derived classes. Private methods can't.
That's the one and only difference between private and protected methods.