William
William

Reputation: 1895

When to override and when to subscribe to delegate?

I've noticed in C# I can handle events in a few different ways, but I'm unsure which one is best to use, look here:

this.Paint += Form1_Paint;

void Form1_Paint(object sender, PaintEventArgs e)
{
        Graphics g = e.Graphics;
        g.DrawEllipse(new Pen(Color.Red, 20), new Rectangle(50, 100, 50, 100));
}

or

protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.DrawEllipse(new Pen(Color.Red, 20), new Rectangle(50, 100, 50, 100));
}

Of course these both preform the same result, and the OnPaint() will normally (If I hadn't changed it) just invoke the Form1_Paint method through a delegate.

But which one of these is best to use?

Thank you

Upvotes: 1

Views: 362

Answers (3)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

Simple, OnPaint overridden method is for myself(I mean the control or form itself). For example: If you want to change how your control look like you will do it in OnPaint overridden method.

Paint event is for others, by that I mean once you decided look of your control but it doesn't suit in some place, you want to make it little better you'll do it by subscribing Paint event.

In other words: OnPaint should be used when you're deciding a look of a Type itself where as Paint event should be used when you're deciding a look of an Instance.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117057

These two approaches are not the same.

It is very possible to write code where the OnPaint method is called, but not to have the Paint method fire.

In fact, the code you have written in your question is exactly this situation.

Your code is missing the base.OnPaint(e); call that actually will fire the event:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Graphics g = e.Graphics;
    g.DrawEllipse(new Pen(Color.Red, 20), new Rectangle(50, 100, 50, 100));
}

So you really should decide if your behaviour could be affected by choosing one over the other.

However, it 99.999% of all code that is properly written there is no distinction.

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

The preferred way is to override the OnPaint method rather than registering to the Paint event. That way you aren't coupling a delegate to your Paint control.

From MSDN:

Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. The OnPaint method also enables derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

Notes to Inheritors: When overriding OnPaint in a derived class, be sure to call the base class's OnPaint method so that registered delegates receive the event.

Upvotes: 4

Related Questions