A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 6.1: Declaring and calling methods

 methods are blocks of code that perform a specific task. They are declared using the method keyword, and you can call them to execute the code within them. Here's a simple tutorial on declaring and calling methods in C#:

Declaring a Method:

using System;

class Program
{
    // Method without parameters and return type
    static void SayHello()
    {
        Console.WriteLine("Hello, world!");
    }

    // Method with parameters and return type
    static int AddNumbers(int a, int b)
    {
        return a + b;
    }

    // Method with parameters and no return type (void)
    static void PrintSum(int num1, int num2)
    {
        int sum = num1 + num2;
        Console.WriteLine($"Sum: {sum}");
    }

    // Main method - entry point of the program
    static void Main()
    {
        // Calling the SayHello method
        SayHello();

        // Calling the AddNumbers method and storing the result
        int result = AddNumbers(5, 7);
        Console.WriteLine($"Sum: {result}");

        // Calling the PrintSum method
        PrintSum(10, 20);
    }
}

Explanation:

  1. SayHello Method:

    • Declared with the static void syntax, indicating it doesn't return a value.
    • Called in the Main method using SayHello();.
  2. AddNumbers Method:

    • Declared with the static int syntax, indicating it returns an integer.
    • Takes two parameters (a and b) and returns their sum.
    • Called in the Main method, and the result is printed.
  3. PrintSum Method:

    • Declared with the static void syntax, indicating it doesn't return a value.
    • Takes two parameters (num1 and num2), calculates their sum, and prints it.
    • Called in the Main method.
  4. Main Method:

    • The entry point of the program.
    • Calls the SayHello, AddNumbers, and PrintSum methods.

Output:

Hello, world!
Sum: 12
Sum: 30

This is a basic example, and you can expand on it by adding methods with different return types, more parameters, and additional logic. Methods are an essential part of organizing and reusing code in C#.