using System;

namespace Metodi;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine("Chiamata a metodo della classe Console.");
     }
}

METHODS IN C#

C sharpC Sharp methods are one of the most important data structures in Object Oriented programming also known as OOP. The function of a method is to enclose code in a block delimited by curly brackets so that it can then be called or, as they say, invoked in other parts of the program. We have encountered a particular method many times, the Main method generated when we create a Console application.

LET’S ANALYZE THE MAIN METHOD IN DETAIL

    • First of all, the name of the method, in this case Main, each method needs a name to be able to be invoked. We have already seen the rules for assigning the name, it must not be a reserved keyword of the language and it must begin with a capital letter.
    • A method can accept input parameters that we provide when we call it, think for example of a method whose task is to calculate the square root of a number (This is just an example because C# provides the Math class for operations of this type). To calculate the square root the method will need the number on which we want the calculation to take place, this is provided immediately after the name of the method closed in round brackets. Even if a method does not accept parameters we must still specify a pair of round brackets (). In the code above our Main method accepts as input parameter (the input parameters can also be more than one) an array of strings called args arrays we will see them in detail later.
    • A method can return a value, think of the example of the square root, obviously the method after calculating it will have to return the result to the caller. The return type immediately precedes the method name, in our example code the word void indicates that this method will not return any value. In the square root example we would have put a double as the return type.
    • The static keyword indicates that this will not be an instance method of a type (this topic will be clearer when we talk about classes) but rather a class method. A class method is called with dot notation, you can see an example of this in the Main method code block where on the Console class followed by a dot the WriteLine method is called, which is also static as you can see.
    • The block of code enclosed in curly brackets is a statement that will execute the method in order, in our case we have only one statement.
    • A method must always have an upper container that encloses it, in the code example I have given you there is the Program class which acts as a container for the only method it encloses. A method is also called class member or class instance member if it is called on the objects of the class (in this case the static keyword is not used).

DEFINE AND DECLARE A METHOD

I have defined a Sum method which takes as input two integers a and b and returns an int and not void as we analyzed in the previous case and which represents the sum of the two values. The variables a, b, and result which collects the sum of a and b, are local variables to the method, as they say their scope of visibility (or scope) is limited in the code block of the Sum method, these variables are not visible outside the method. We encounter a new return keyword followed by the result variable.

THE RETURN INSTRUCTION

This statement immediately causes the method to end and return to the caller, i.e. at the point where we invoked the Sum method in Main. This instruction is mandatory for methods that return a value, it may or may not be present for methods that return void, i.e. those that do not return a value. If there is no return statement then the method determines the last curly bracket that delimits the block of code and returns to the caller. The sum is placed in the variable x, which is also an integer type variable, then the program flow continues with the instruction Console.WriteLine(x); It is important to note that in this case dot notation was not used as sum is a static method defined in the Program class, however if we want to have greater clarity in the code we can use dot notation.

int x = Program . Sum (50.25);

OVERLOAD OF A METHOD

  • The signature of a method (or signature) is made up of the name of the method, the number and type of parameters it takes as input and the type of return. Having said this, we can introduce n methods called Sum into the program but with different signatures, i.e. having for example different types of input parameters. You can see some examples in the code.

RECURSIVE METHODS

static void RecursiveMethod ()

{ RecursiveMethod ();

}

The method calls itself. We must be careful to introduce a base case, that is, a test condition that puts an end to the recursion, otherwise we would enter an infinite loop that crashes the program.

VISUAL STUDIO CODE

using System;
namespace Metodi;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine("Chiamata a metodo della classe Console.");
        var x = Somma(50, 25);
        Console.WriteLine(x); //75
        var y = Somma(14.1f, 16.9f);
        Console.WriteLine(y);
        var z = Somma(14.1m, 16.9m);
        Console.WriteLine(z);
        Console.Write("Inserisci un numero ");
        var fatt = Convert.ToInt32(Console.ReadLine());
        var fattoriale = Fattoriale(fatt);
        Console.WriteLine($"Il fattoriale di {fatt} è : {fattoriale}");
    }

    //DEFINIZIONE DEL METODO SOMMA
    private static int Somma(int a, int b)
    {
        var result = a + b;
        return result;
    }

    //OVERLOAD DEL METODO SOMMA
    private static float Somma(float a, float b)
    {
        var result = a + b;
        return result;
    }

    //OVERLOAD DEL METODO SOMMA
    private static decimal Somma(decimal a, decimal b)
    {
        var result = a + b;
        return result;
    }

    //METODI RICORSIVI CALCOLARE IL FATTORIALE DI UN NUMERO.
    private static int Fattoriale(int n)
    {
        if (n == 0) //CASO BASE CHE PERMETTE DI USCIRE DAL LOOP.
            return 1;
        return n * Fattoriale(n - 1);
    }

    private static double RadiceQuadrata(int a)
    {
        return Math.Sqrt(a);
    }
}
Calculation of the factorial of a number

IN-DEPTH ON THE METHODS

Methods in C# are blocks of code that perform specific operations and can be called from other parts of the program. They are defined within classes and structures. Here is an overview of methods in C#:

Declaration of a Method

A method in C# is declared with an access modifier, a return type, a name, and an optional parameter list. Example:

public int Add ( int a, int b)
{

    return a + b;
}

Access Modifiers

Access modifiers determine method visibility:

public : Accessible from any other part of the code.

private : Accessible only within the same class.

protected : Accessible within the same class and derived classes.

internal : Accessible within the same assembly.

protected internal : Accessible from within the same assembly or from derived classes.

Return Types

The return type specifies the type of data that the method will return. If the method returns nothing, void is used:

public void DisplayMessage ()

{

    Console.WriteLine(” Hello, World! “);

}

Parameters

Parameters allow you to pass data to methods. There are also optional parameters and parameters with params:

public void PrintNumbers (params int [] numbers)

{

      foreach ( int number in numbers)

     {

          Console.WriteLine( number );

     }

}

Overloading

C# allows you to define multiple methods with the same name but with different signatures (number or type of parameters):

public int Multiply ( int a, int b)
{

    return a * b;
}

public double Multiply ( double a, double b)
{

    return a * b;
}

Static methods

Static methods belong to the class rather than specific instances and can be called without instantiating the class:

public static void ShowMessage ()

{

   Console.WriteLine(” This is a static method. “);

}

Extension Methods

They allow you to add methods to existing types without modifying them:

public static class StringExtensions

{

    public static bool IsNumeric ( this string str)

    {

       return int.TryParse (str, out _ );

    }

}

Asynchronous methods

Used for asynchronous operations, they allow you not to block the calling thread:

public async Task<string> GetDataAsync()

{

     await Task.Delay(1000); // Simulate an asynchronous operation

     return “Data”;

}

Complete Example

Here is a complete example that includes various types of methods:

using System;
public class Codice
{
    public static void Main()
    {
        Codice p = new Codice();
        p.DisplayMessage();
        int result = p.Add(5, 7);
        Console.WriteLine($"Add: {result}");

        result = Multiply(3, 4);
        Console.WriteLine($"Multiply: {result}");

        string data = p.GetData().Result;
        Console.WriteLine($"GetData: {data}");

        string numStr = "123";
        bool isNumeric = numStr.IsNumeric();
        Console.WriteLine($"IsNumeric: {isNumeric}");
    }

    public void DisplayMessage()
    {
        Console.WriteLine("Hello, World!");
    }

    public int Add(int a, int b)
    {
        return a + b;
    }

    public static int Multiply(int a, int b)
    {
        return a * b;
    }

    public async Task<string> GetData()
    {
        await Task.Delay(1000); // Simula un'operazione asincrona
        return "Data";
    }
}

public static class StringExtensions
{
    public static bool IsNumeric(this string str)
    {
        return int.TryParse(str, out _);
    }
}

LINKS TO PREVIOUS POSTS