Language: EN

csharp-retorno-funciones

Return of functions in C#

The return of a function is the way in which a function can return a value to the code that called it. The reserved word return is used for this purpose.

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 to not return any value. This is indicated by the void type.

It is only possible to return one value. Although we can return a group of values, such as a collection, a tuple or a class.

Return of void

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 greet() function 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

A function can return a specific value. For this we use return. At the moment a return is reached, the execution of the function stops, and the control is returned to the function that invoked it.

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 wouldn't be executed
}

Logically, the return type of the function must match the type of the value that 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 group of values.

Using Classes or Structures

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" };
}

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) GetInfo()
{
    return (42, "Example");
}

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

Returning collections

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

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 ShowMessage(string message)
{
    Console.WriteLine(message); // Print the received message
}

// Usage
ShowMessage("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 CalculateCircleArea(double radius)
{
    return Math.PI * radius * radius; // Return the calculated area
}

// Usage
double area = CalculateCircleArea(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 the product of two numbers.

// Function that calculates the sum and the product of two numbers
public (int sum, int product) CalculateSumAndProduct(int a, int b)
{
    return (a + b, a * b); // Return a tuple with the sum and the product
}

// Usage
var result = CalculateSumAndProduct(3, 4); // Call the function and store the result in a tuple
Console.WriteLine($"Sum: {result.sum}, Product: {result.product}"); // Print the sum and the 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 Person class.

// Class that represents a person with name and age
public class Person
{
    public string Name { get; set; } // Property for the name
    public int Age { get; set; } // Property for the age
}

// Function that creates an instance of the Person class
public Person CreatePerson(string name, int age)
{
    return new Person { Name = name, Age = age }; // Return a new instance of Person
}

// Usage
Person person = CreatePerson("John", 30); // Call the function and store the result in a variable
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); // Print the name and the age of the person