Language: EN

csharp-retorno-funciones

Return of functions in C#

The return of a function is a value that after its completion (and optionally) a function can return to the code that called it. For this, the reserved word return is used.

This value can be of any data type, including basic types (like int, float, string), complex types (like objects and structures), and even custom data types.

It is also possible for a function not to return any value. This is indicated by the type void.

On the other hand, only one value can be returned. Although we can return a grouping of values (like a collection, a tuple, or a class).

Void Return

When a function does not need to return any value, it is declared with the return type void. These functions generally perform actions (like modifying the state of an object or printing to the console).

For example, the function greet() only performs an action, it does not need to return any value. In that case, we use the reserved word void.

public void Greet()
{
    Console.WriteLine("Hello!");
}

Return of a Value

As we have said, a function can return a single value. For this, the keyword return is used. When a return is reached, the execution of the function stops, and control is returned to the function that invoked it.

For example, the function Add returns a value of type int.

public int Add(int a, int b)
{
    return a + b;
	
	// if there were something here, it would not be executed
}

Logically, the return type of the function must match the type of the value we return.

Return of Multiple Values

As we said, it is only possible to return a single value with a function. However, we can return a grouping of values.

For example, we can return multiple values encapsulated in a class or structure.

public class Result
{
    public int Number { get; set; }
    public string Text { get; set; }
}

public Result GetResult()
{
    return new Result { Number = 42, Text = "Example" };
}

This is the most common way to return multiple values in C#.

We can also use tuples when we want to return multiple values from a function.

public (int, string) GetData()
{
    return (42, "Example");
}

This is useful when the grouping we are going to return is temporary, and it is not worth creating a structure or object solely for the return.

Functions can also return objects of any type of collections, such as arrays, lists, dictionaries.

For example like this.

public List<int> GetList()
{
    return new List<int> { 1, 2, 3, 4, 5 };
}

Practical Examples