Is it correct to call a method, and pass its null parameters?

13

For example, I have the click event of a button calling the method below:

 //Evento
 this.serviçoToolStripMenuItem1.Click += new System.EventHandler(this.Nivel_Serv_Click);

 //Metodo
 private void Nivel_Serv_Click(object sender, EventArgs e) //tipo 3 serviço
 {
    //faz alguma coisa....
 }

In another method, I performed the above method call:

 Nivel_Serv_Click(null, null);

Is it right to do this? or would it be a gambiarra?

    
asked by anonymous 27.06.2017 / 12:36

3 answers

12

Yes, since there is no overhead that can deal with your call without arguments. But it may not be the most appropriate.

I would only question if it's what you want, usually when you receive a notification that the object has had an event you're likely to want to know or do something with this object and discard it looks strange but has cases for that.

I'd say it's gambiarra , but the C # event engine is a gambiarra. Avoiding gambiarras is not always pragmatic, there is good gambiarra.

But this method is not called by you, so it will not have null arguments. If you want to call an event method directly, then it might be a bigger hit.

If you want to have a method that does not need these parameters, create such a method and call it, or use a method (see the LINQ response ). If you want it to run inside the event method, call it inside the event method.

    
27.06.2017 / 12:57
11

If you want to execute the code {faz alguma coisa} either when the menu option is clicked by the user or directly by a call of your code, the "most correct" code will be to create a method with this code:

//Evento
 this.serviçoToolStripMenuItem1.Click += new System.EventHandler(this.Nivel_Serv_Click);

 //Método
 private void Nivel_Serv_Click(object sender, EventArgs e) //tipo 3 serviço
 {
    FazAlgumaCoisa();
 }

private void FazAlgumaCoisa()
{
    //faz alguma coisa....
}

When the menu item is clicked the system calls Nivel_Serv_Click() which for its part calls FazAlgumaCoisa() .

When you want to call it via code, call it like this:

FazAlgumaCoisa();
    
27.06.2017 / 12:56
8
Another important point is that all controls that are buttons have a method called PerformClick , it triggers the click event of the button.

Notice that there is no error in calling the event method by passing both arguments as null if you do not use the parameters within Nivel_Serv_Click .

Usually the sender is used, since it identifies the control that triggered the event. In this case, it is best to use PerformClick() .

    
27.06.2017 / 14:01