Language: EN

csharp-que-son-las-funciones

What are and how to use functions in C#

A function is a block of reusable code that performs a specific task when called or invoked from elsewhere in the program.

Functions are a fundamental part of programming, as they allow you to divide the code into smaller, more manageable units. This makes it easier to understand, maintain, and debug the software.

Functions in C# can take zero or more parameters as input, perform calculations or manipulations based on those parameters, and return an optional result as output.

The basic syntax for defining a function in C# is as follows:

[modifier] return_type function_name([parameter_list])
{
    // Function code
    return return_value; // Optional
}
  • Modifier: Can be public, private, protected, among others, to define the access level of the function.
  • Return type: Specifies the data type that the function will return as a result. It can be void if the function does not return any value.
  • Function name: It is the unique identifier of the function that will be used to invoke it from other parts of the program.
  • Parameter list: Variables that are used to pass information to the function when it is called.
  • Function code: Set of instructions that will be executed when the function is called.
  • Return value: The result returned by the function, optionally.

Basic Example

Next, is a basic example of a function that adds two numbers:

public int Sum(int num1, int num2)
{
    return num1 + num2;
}

In this example, the Sum function takes two parameters num1 and num2, performs the addition operation, and returns the result.

Calling functions

To call (invoke) a function and execute its code, simply use the function name followed by parentheses, passing the values of the parameters if necessary.

Here’s an example of code that calls the Sum function and stores the result in a variable:

int result = Sum(5, 3);

In this case, the Sum function is called with the values 5 and 3 as arguments, and returns the result 8, which is assigned to the variable result.

Parameters

Functions in .C# can have one or more input parameters, which are values passed to the function when it is called. These parameters are used within the function to perform calculations and determine the result to be returned.

For example, in the following example the CalculateRectangleArea function has two parameters, width and height, both of type double.

double CalculateRectangleArea(double width, double height)
{
	// Code to calculate the area of a rectangle
	double area = width * height;
	return area;
}

Return value

Functions can return a value as a result using the return keyword. The type of the returned value must match the return type specified in the function signature.

For example, in the CalculateCircleArea function returns a double type.

static double CalculateCircleArea(double radius)
{
	// Code to calculate the area of a circle
	double area = Math.PI * radius * radius;
	return area;  // return of area
}

Only one value can be returned from a function. Although it is possible to return a grouping of several values (such as a tuple, struct, or an object).

Functions without return

If a function does not return a value, the void keyword is used as the return type.

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

Practical examples

Function to determine if a number is even or odd

This function determines if a number is even or odd.

public static string EvenOdd(int number)
{
    if (number % 2 == 0) // Checks if the number is divisible by 2
    {
        return "even"; // Returns "even" if the number is divisible by 2
    }
    else
    {
        return "odd"; // Returns "odd" if the number is not divisible by 2
    }
}

Function to calculate the area of a circle

This function calculates the area of a circle given its radius.

public static double CalculateCircleArea(double radius)
{
    return Math.PI * radius * radius; // Calculates the area using the πr² formula
}

Function to determine the maximum of two numbers

This function returns the larger of two numbers.

public static int Maximum(int a, int b)
{
    if (a > b) // Compares the two numbers
    {
        return a; // Returns 'a' if it is greater than 'b'
    }
    else
    {
        return b; // Returns 'b' if it is greater or equal to 'a'
    }
}

Function to convert Celsius to Fahrenheit

This function converts a temperature from Celsius to Fahrenheit.

public static double CelsiusToFahrenheit(double celsius)
{
    return (celsius * 9/5) + 32; // Applies the conversion formula
}

Function to check if a number is prime

This function determines if a number is prime.

public static bool IsPrime(int number)
{
    if (number <= 1) return false; // Numbers less than or equal to 1 are not prime
    for (int i = 2; i < number; i++) // Iterates from 2 to number - 1
    {
        if (number % i == 0) return false; // If the number is divisible by 'i', it is not prime
    }
    return true; // If no divisor was found, the number is prime
}

Function to calculate the sum of an array of integers

This function calculates the sum of all elements in an array of integers.

public static int SumArray(int[] numbers)
{
    int sum = 0; // Initializes the sum to 0
    foreach (int number in numbers)
    {
        sum += number; // Adds each element of the array to 'sum'
    }
    return sum; // Returns the total sum
}

These examples are intended to show how to use Functions. It does not mean that it is the best way to solve the problem they address.