How the parameters received in a method should be treated

1

Cordial greeting.

I am a student of development, I am developing a program and in a class I have a method with several parameters, the question that arises is that within the method as I should treat those parameters, should I assign them to a local variable? or I can work on those objects without needing to assign them to a local variable. Example: I have the following method.

 public void CambiarTextoTextBox(TextBox textBoxAModificar)
    {
     TextBox textBox=textBoxAModificar;
     textBox.ForeColor = Color.Black;
     textBox.Text="Hola";  
    }


 public void CambiarTextoTextBox(TextBox textBoxAModificar)
    {
     textBoxAModificar.ForeColor = Color.Black; 
     textBoxAModificar.Text="Hola";
    }

I clarify that I know that the two methods work correctly, my doubt is that which is the correct one, which would be a good practice.

    
asked by Diego Giraldo 25.03.2018 в 17:53
source

1 answer

2

The parameters in C # are passed as references to the original, so if you assign it to a local variable and modify it, it has the same effect as modifying it directly, it is redundant.

That is, in your example the two functions do the same. The "correct" way would be the second, since it does not make sense to assign it to another variable and spend that memory in the reference.

Another thing is if you want to use those parameters outside your function in that same class, so if you should assign them to a variable to work with it without passing them as a parameter. Example:

private TextBox textBox;

public void CambiarTextoTextBox(TextBox textBoxAModificar)
{
    this.textBox=textBoxAModificar; // Lo asignamos a la variable de esta clase.
}

public void otraFuncion()
{ 
    // Modificamos el valor como queramos
    this.textBox.ForeColor = Color.Black;
    this.textBox.Text="Hola";  
}
    
answered by 25.03.2018 в 18:19