How to transform a method into a class?

3

I have the following in a form:

public form1()
{
    InitializeComponent();
    this.FormClosing += new FormClosingEventHandler(this.confirmarFechamento_FormClosing);
}
private void confirmarFechamento_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        var result = MessageBox.Show(this, "Você tem certeza que deseja sair?", "Confirmação", MessageBoxButtons.YesNo);
        if (result != DialogResult.Yes)
        {
            e.Cancel = true;
        }
    }
}

How could I turn this into a class and just call it as a method? In case it would be class confirmarFechamento that has method confirmarFechamento , and in form1 would have the call of method confirmarFechamento .

    
asked by anonymous 21.03.2014 / 05:23

2 answers

5

Just right click on your project, go to add and then click on class. I recommend that you name the class as a noun that represents it and for the method the action it does effectively. Your code would look like this +/-:

public form1()
{
    InitializeComponent();
    this.FormClosing += new FormClosingEventHandler(this.confirmarFechamento_FormClosing);
}


private void confirmarFechamento_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        if (! new Fechamento().ConfirmarFechamento())
            e.Cancel = true;
    }
}




public class Fechamento
{
    public bool ConfirmarFechamento()
    {
        var result = MessageBox.Show("Você tem certeza que deseja sair?", "Confirmação", MessageBoxButtons.YesNo);
        return result == DialogResult.Yes;
    }
}

But I do not think it would be very useful to create a class just for that.

    
21.03.2014 / 12:57
0

Well you can create a class to handle all your Forms, so you would be more object-oriented, which would make your code reusable. So when you need a method that does some action for your Forms, be validate, close, cancel, save and etc ... Just reference it there and "abuse it", lol ... Hugs.

    
21.03.2014 / 19:20