How to turn a method into a class?

Asked

Viewed 239 times

3

I have the following on 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 a method? In case it would be class confirmarFechamento who has the method confirmarFechamento, and in Form1 would have the call of the method confirmarFechamento.

  • What would be the purpose of doing this? You want to take advantage of the method in more than one form, that’s it?

  • 1

    If so, you could make a Baseform and put this event in it

  • What is your goal? use the method in several places?

  • Yes, I want to take advantage of the method, use in several different classes.

2 answers

5


Just right click on your project, go to add and then click on class. I recommend that you name the class with a noun that represents it and the method with the action that it actually does. 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 don’t think it would be very useful to create a class just for that.

  • 2

    Another option would be Fechamento and ConfirmarFechamento be static.

0

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

  • 1

    In case, how could I do it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.