Search code examples
c#reusability

How to make this method reusable?


I have copy pasted this method into two classes. I would rather reuse it from the first class. This is in a windows forms application.

public void defineMapArea()
{
    PictureBox pictureBox1 = new PictureBox();

    // Dock the PictureBox to the form and set its background to white.
    pictureBox1.Dock = DockStyle.Fill;
    pictureBox1.BackColor = Color.White;

    // Connect the Paint event of the PictureBox to the event handler method.
    pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);

    // Add the PictureBox control to the Form. 
    this.Controls.Add(pictureBox1);
}

The only thing that needs to change in the method from one class to another is the "this" keyword which refers to the class, as hovering over "this" confirms. I thought maybe "this" will just apply to the class calling the method, but i think it still refers to the class that the method is defined in. It would be fantastic to simply pass a class as a parameter, but i'm thinking that doesn't work as i have attempted that.

Any help appreciated. Thanks!


Solution

  • I would do so:

    public static void DefineMapArea(Form form, Action<object, PaintEventArgs> handler)
    {
        if (form == null)
        {
            throw new ArgumentNullException("form");
        }
    
        if (handler == null)
        {
            throw new ArgumentNullException("handler");
        }
    
        PictureBox pictureBox1 = new PictureBox();
    
        // Dock the PictureBox to the form and set its background to white.
        pictureBox1.Dock = DockStyle.Fill;
        pictureBox1.BackColor = Color.White;
    
        // Connect the Paint event of the PictureBox to the event handler method.
        pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(handler);
    
        // Add the PictureBox control to the Form. 
        form.Controls.Add(pictureBox1);
    }
    

    You can call it (assuming from your form):

    DefineMapArea(this, (sender, e) =>
    {
        // ... put here your code
    });
    

    Or

    DefineMapArea(this, Handler);
    
    void Handler(object sender, PaintEventArgs e)
    {
        // ... put here your code
    }