user2602079
user2602079

Reputation: 1403

C# - make this event handler reusable?

I have two classes with the same event handler essentially, but the event handler calls the same method with different jagged List arguments.

public void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    drawMap(e, myTextFileHandler.getMapCellWalls(), myTextFileHandler.getMapCellPositions());
}

public void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    myGameForm.drawMap(e, mapCellWallList, mapCellPositionList);
}

Can i just reuse the pictureBox1_Paint by adding two parameters which are the jagged lists used in drawMap()?

I did try it but then i noticed that when i call pictureBox1_Paint, i do not even give it one parameter, which very much confused me. EG:

private void LevelDesignerForm_Load(object sender, EventArgs e)
{
    myGameForm.defineMapArea(this, this.pictureBox1_Paint);
}

What is the best practice way? Because i feel as if i copy and pasted a method almost. Any help appreciated. Thanks

Upvotes: 0

Views: 616

Answers (1)

Krishna Sarma
Krishna Sarma

Reputation: 1860

First, you cannot call an event handler defined in a different class directly. Though you can do this by editing the event handler mapping in InitializeComponent something like below, its not good practice.

this.Paint += new System.EventHandler(new class1().pictureBox1_Paint);

Secondly, you cannot change the signature of the event handler. If you observe the above code, you are just giving the name of method. So, you don't have provision to pass the data to it.

However, you can use the Tag property of the components if you really wants to go with this approach. You can store any object (of course only one) into it and in the event hanlder you can typecast to its original type and process.

I feel the best practice is what you have right in hand.

Upvotes: 1

Related Questions