The return of a function is a value that after its completion (and optionally) a function can return to the code that called it. This is done using the reserved word return
.
This value can be of any data type, including basic types (such as int
, float
, string
), complex types (such as 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, it is only possible to return one value. Although we can return a grouping of values (such as a collection, a tuple, or a class).
If you want to learn more about Return in functions
consult the Introduction to Programming Course read more
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 (such as modifying the state of an object or printing to the console).
For example, the function saludar()
only performs an action, it does not need to return any value. In that case, we use the reserved word void
.
public void Saludar()
{
Console.WriteLine("Hello!");
}
Return of a Value
As we said, a function can return a single value. To do this, we use the keyword return
. When a return
is reached, the execution of the function stops, and control is returned to the function that invoked it.
For example, the Sumar
function returns a value of type int
.
public int Sumar(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.
Using Classes or Structures
For example, we can return multiple values encapsulated in a class or structure.
public class Resultado
{
public int Numero { get; set; }
public string Texto { get; set; }
}
public Resultado ObtenerResultado()
{
return new Resultado { Numero = 42, Texto = "Example" };
}
This is the most common way to return multiple values in C#.
Using Tuples
We can also use tuples when we want to return multiple values from a function.
public (int, string) ObtenerDatos()
{
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 just for the return.
Return of Collections
Functions can also return objects of any type of collections, such as arrays, lists, dictionaries.
For example like this.
public List<int> ObtenerLista()
{
return new List<int> { 1, 2, 3, 4, 5 };
}
Practical Examples
Example of a void function
In this example, it shows how to define a function that does not return any value using the return type void
.
// Function that prints a message to the console
public void MostrarMensaje(string mensaje)
{
Console.WriteLine(mensaje); // Print the received message
}
// Usage
MostrarMensaje("Hello, World!"); // Call the function with the message "Hello, World!"
Example of a function with return value
In this example, it shows how to define a function that returns a value. In this case, it calculates the area of a circle.
// Function that calculates the area of a circle given its radius
public double CalcularAreaCirculo(double radio)
{
return Math.PI * radio * radio; // Return the calculated area
}
// Usage
double area = CalcularAreaCirculo(5.0); // Call the function and store the result
Console.WriteLine($"The area of the circle is: {area}"); // Print the area of the circle
Example of a function with tuple return
In this example, it shows how to define a function that returns a tuple. In this case, it calculates the sum and product of two numbers.
// Function that calculates the sum and product of two numbers
public (int suma, int producto) CalcularSumaYProducto(int a, int b)
{
return (a + b, a * b); // Return a tuple with the sum and product
}
// Usage
var resultado = CalcularSumaYProducto(3, 4); // Call the function and store the result in a tuple
Console.WriteLine($"Sum: {resultado.suma}, Product: {resultado.producto}"); // Print the sum and product
Example of a function with class return
In this example, it shows how to define a function that returns an instance of a class. In this case, it creates an instance of the Persona
class.
// Class that represents a person with name and age
public class Persona
{
public string Nombre { get; set; } // Property for the name
public int Edad { get; set; } // Property for the age
}
// Function that creates an instance of the Persona class
public Persona CrearPersona(string nombre, int edad)
{
return new Persona { Nombre = nombre, Edad = edad }; // Return a new instance of Persona
}
// Usage
Persona persona = CrearPersona("Luis", 30); // Call the function and store the result in a variable
Console.WriteLine($"Name: {persona.Nombre}, Age: {persona.Edad}"); // Print the name and age of the person