Supongamos el siguiente código, sin ninguna palabra clave ref
, que obviamente no reemplazará la variable aprobada, ya que se pasa como valor.Parámetro de matriz que pasa en C#: ¿por qué es implícitamente por referencia?
class ProgramInt
{
public static void Test(int i) // Pass by Value
{
i = 2; // Working on copy.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(i);
Console.WriteLine(i);
Console.Read();
// Output: 1
}
}
Ahora que tienen esa función de trabajo como se esperaba, se podría añadir la palabra clave ref
como de costumbre:
class ProgramIntRef
{
public static void Test(ref int i) // Pass by Reference
{
i = 2; // Working on reference.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(ref i);
Console.WriteLine(i);
Console.Read();
// Output: 2
}
}
Ahora estoy perplejo en cuanto a por qué los miembros de la matriz cuando se pasa de funciones se transmiten implícitamente referencia. ¿No son los tipos de valores de matrices?
class ProgramIntArray
{
public static void Test(int[] ia) // Pass by Value
{
ia[0] = 2; // Working as reference?
}
static void Main(string[] args)
{
int[] test = new int[] { 1 };
ProgramIntArray.Test(test);
Console.WriteLine(test[0]);
Console.Read();
// Output: 2
}
}
¿Por qué hacer una wiki? – jsmith