csharp-retorno-funciones

Return of functions in C#

  • 5 min

The return of a function is a value that, upon its completion (and optionally), a function can return to the code that called it. For this, the reserved keyword 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 void type.

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).

If you want to learn more, check out the Introduction to Programming Course

Void Return

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

For example, the greet() function only performs an action; it doesn’t need to return any value. In that case, we use the reserved keyword void.

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

Returning a Single Value

As mentioned, a function can return a single value. For this, the return keyword is used. The moment a return is reached, the function’s execution stops, and control is returned to the calling function.

For example, the Add function 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
}
Copied!

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

Returning Multiple Values

As we said, only a single value can be returned from a function. However, we can return a grouping of values.

For example, we can return multiple values by encapsulating them 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" };
}
Copied!

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");
}
Copied!

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

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

For example, like this.

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

Practical Examples