Pasar parámetros (Guía de programación de C#)Passing Parameters (C# Programming Guide)
En C#, los argumentos se pueden pasar a parámetros por valor o por referencia.In C#, arguments can be passed to parameters either by value or by reference. El paso de parámetros por referencia permite a los miembros de funciones, métodos, propiedades, indexadores, operadores y constructores cambiar el valor de los parámetros y hacer que ese cambio persista en el entorno de la llamada.Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. Para pasar un parámetro por referencia con la intención de cambiar el valor, use la palabra clave ref
o out
.To pass a parameter by reference with the intent of changing the value, use the ref
, or out
keyword. Para pasar un parámetro por referencia con la intención de evitar la copia pero no modificar el valor, use el modificador in
.To pass by reference with the intent of avoiding copying but not changing the value, use the in
modifier. En los ejemplos de este tema, para simplificar, solo se usa la palabra clave ref
.For simplicity, only the ref
keyword is used in the examples in this topic. Para obtener más información sobre la diferencia entre in
, ref
y out
, vea in, ref y out.For more information about the difference between in
, ref
, and out
, see in, ref, and out.
En el ejemplo siguiente se muestra la diferencia entre los parámetros de valor y de referencia.The following example illustrates the difference between value and reference parameters.
class Program
{
static void Main(string[] args)
{
int arg;
// Passing by value.
// The value of arg in Main is not changed.
arg = 4;
squareVal(arg);
Console.WriteLine(arg);
// Output: 4
// Passing by reference.
// The value of arg in Main is changed.
arg = 4;
squareRef(ref arg);
Console.WriteLine(arg);
// Output: 16
}
static void squareVal(int valParameter)
{
valParameter *= valParameter;
}
// Passing by reference
static void squareRef(ref int refParameter)
{
refParameter *= refParameter;
}
}
Para obtener más información, vea los temas siguientes:For more information, see the following topics:
Pasar parámetros de tipo de valorPassing Value-Type Parameters
Pasar parámetros Reference-TypePassing Reference-Type Parameters
Especificación del lenguaje C#C# Language Specification
Para obtener más información, vea la sección Listas de argumentos de Especificación del lenguaje C#.For more information, see Argument lists in the C# Language Specification. La especificación del lenguaje es la fuente definitiva de la sintaxis y el uso de C#.The language specification is the definitive source for C# syntax and usage.