C# Methods

In C#, a method is a block of code that performs a specific task or operation. It is a fundamental concept in programming that allows you to organize code into reusable and modular units. Methods define behaviors that can be executed when called from other parts of the program.

Defining a Method

A method is defined with the following structure:


<access_modifier> <return_type> <method_name>(<parameters>)
{
    // Method body: code to be executed
}

Explanation:

  • Access Modifier: Specifies the visibility of the method (e.g., public, private, protected). It determines whether the method can be accessed from outside the class.
  • Return Type: Specifies the type of value that the method returns. This can be any valid type (int, double, string, void for no return, etc.). If a method doesn’t return a value, its return type is void.
  • Method Name: The identifier by which the method is called. It should follow the C# naming conventions.
  • Parameters: These are optional. They define the data that the method needs to perform its task. A method can have zero or more parameters, and they are passed to the method when it is called.
  • Method Body: The block of code that defines the functionality of the method.

Example: A simple method that multiply two numbers


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

Note: This method takes two integers, multiply them, and returns the result as an integer.

Calling a Method

You can call a method by using its name and passing the required arguments (if any).

Syntax:


<method_name>(<arguments>);

Example:


using System;

public class ProgramExample
{
    public int MultiplyNumbers(int a, int b)
    {
        return a * b;
    }

    public static void Main()
    {
        ProgramExample pe = new ProgramExample();
        int result = pe.MultiplyNumbers(10, 20);
        Console.WriteLine("The result is: " + result);  // Output: The result is: 200
    }
}

Output:

200

Method Return types and void methods

Void Methods: Methods that do not return any value.


public void Greetings()
{
    Console.WriteLine("Hello, Friends!");
}

Methods with Return Values: Methods that return a value of a specific type (e.g., int, string).


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