Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a base class event call a private method?

Tags:

c#

base

events

I have a question regarding raising base class events. I am currently reading the MSDN C# Programming Guide and I cannot understand one thing from the below article:

http://msdn.microsoft.com/en-us/library/vstudio/hy3sefw3.aspx

public void AddShape(Shape s)
{
    _list.Add(s);
    s.ShapeChanged += HandleShapeChanged;
}

OK, so we are registering the delegate with an event and we'll be calling the private method HandleShapeChanged when the event is raised.

public void Update(double d)
{
    radius = d;
    area = Math.PI * radius * radius;
    OnShapeChanged(new ShapeEventArgs(area));
}

protected override void OnShapeChanged(ShapeEventArgs e)
{
    base.OnShapeChanged(e);
}

And here we are calling the base class method OnShapeChanged, which, in success, will fire the event. But the event is based in the Shape class, so how can it access the method HandleShapeChanged, which is private?

I have just started to learn the language, so please bear with me. My understanding of this example may be well off target.

like image 453
Kapol Avatar asked Nov 30 '13 21:11

Kapol


2 Answers

I see the way you are thinking, it feels like another class is calling a private method. But no, the best way to think about it is that access rules are checked when the delegate is created, not when it is invoked. And that of course is no problem, the class can access its own private method.

Also checking it when it is invoked would be lousy, that would require making the event handler public. And handling events is almost always a very private implementation detail of a class that no external code should ever be allowed to call directly. Since that would mean that you couldn't be sure in your event handler that it was actually the event that triggered the call. That's bad, very bad.

like image 79
Hans Passant Avatar answered Nov 05 '22 23:11

Hans Passant


The event is invoking the delegate. It doesn't matter what code is in the delegate. Since the method is not being invoked explicitly, access rules do not apply.

Note also that this has nothing to do with the fact that the event is in a base class. The exact same thing would happen even if the event were in a totally unrelated class.

like image 33
John Saunders Avatar answered Nov 05 '22 21:11

John Saunders