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
?
Protected methods can be called from derived classes. Private methods can't.
That's the one and only difference between private and protected methods.
Keep this in mind too: If you have a button and that button's OnClick is set to 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:
Some aspects of .NET such as ASP.NET create subclasses of your code-behind class at runtime. So an ASP.NET Page class for example inherits from its codebehind class. By making the method protected, the dynamically generated page class can easily hook up a button click event to a protected method in the base class that handles it.
Often 'protected' is used when you want to have a child class override an otherwise 'private' method.
So we have the override behavior we know and love from inheritance, without unnecessarily exposing the InternalUtilityMethod to anyone outside our classes.
If you have an inherited form (or any class for that matter), you would be able to invoke this function from within the sub-class.
Protected Methods are just like private methods. They could be accessed only by the members of the class. Only difference is unlike private members, protected members could be accessed by the derived classes as well.