Language: EN

csharp-parametros-funciones

Function parameters in C#

The parameters are variables defined in the declaration of a function and are used to receive values when the function is invoked.

Parameters allow functions to be more reusable and modular, as they allow different data to be passed to the same function.

Value and reference parameters

Value parameters

Value parameters are the most common. When parameters are passed by value, a copy of the value is passed to the function, which means that any modification inside the function does not affect the original value.

public void Increment(int number)
{
    number++;
    Console.WriteLine(number); // Shows 6
}

int value = 5;
Increment(value);
Console.WriteLine(value); // Shows 5

Reference parameters

Passing parameters by reference allows the function to modify the original value of the passed variable. This is achieved using the ref keyword.

public void Increment(ref int number)
{
    number++;
}

int value = 5;
Increment(ref value);
Console.WriteLine(value); // Shows 6

In and out parameters

Out output parameters

The out parameters are similar to the ref parameters, but are mainly used to return multiple values from a function. It is mandatory to assign a value to the out parameter inside the function before it ends.

public void GetValues(out int a, out int b)
{
    a = 1;
    b = 2;
}

int x, y;
GetValues(out x, out y);
Console.WriteLine($"x: {x}, y: {y}"); // Shows x: 1, y: 2

In input parameters

The in parameters allow passing arguments by reference but ensure that they will not be modified by the function.

public void ShowValue(in int number)
{
    Console.WriteLine(number);
}

int value = 5;
ShowValue(value); // Shows 5

Optional parameters

C# allows defining optional parameters, which are those that have a default value and can be omitted when calling the function.

public void Greet(string name = "World")
{
    Console.WriteLine($"Hello, {name}!");
}

Greet(); // Shows "Hello, World!"
Greet("Juan"); // Shows "Hello, Juan!"

Named parameters

Named parameters allow explicitly specifying the names of the parameters when calling a function, improving readability and allowing some optional parameters to be omitted.

public void CreatePerson(string name, int age, string city = "Unknown")
{
    Console.WriteLine($"{name}, {age} years, {city}");
}

CreatePerson(age: 30, name: "Ana"); // Shows "Ana, 30 years, Unknown"

Variable parameters

Variable parameters allow passing a variable number of arguments to a function using the params keyword. Only one params parameter can be used and it must be the last in the parameter list.

public void PrintNumbers(params int[] numbers)
{
    foreach (int number in numbers)
    {
        Console.WriteLine(number);
    }
}

PrintNumbers(1, 2, 3, 4, 5); // Shows 1 2 3 4 5