Open In App

C# | Methods

Methods are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides a better readability of code. So basically, a method is a collection of statements that perform some specific task and return the result to the caller. A method can also perform some specific task without returning anything.
 

Example : 



// Method Name --> GetCircleArea()
// Return Type ---> double
static double GetCircleArea(double radius)
{
    const float pi = 3.14F;
    double area = pi * radius * radius;
    return area;
}

 

Method Declaration



Method declaration means the way to construct method including its naming. 

Syntax :  

<Access_Modifier> <return_type> <method_name>([<param_list>])

 

In C# a method declaration consists of the following components as follows :

Method Signature : Method Signature is defined by mainly two parameters(number of parameters, type of the parameters and order of the parameters), One of them is Method Name and second one is its Parameter list.
Method Naming : Name of a method or a function in any programming language whether in C++ or Java or C# holds great importance and is mainly used in order to call that method for its execution. For example, findSum, computeMax, setX and getX etc. There are certain pre-defined rules for naming methods which a user should follow :

These rules are not mandatory, but recommendable. Generally, a method has a unique name within the class in which it is defined but sometime a method might have the same name as other method names within the same class as method overloading is allowed in C#.
The Method Body : As discussed above the body of the method consists of statements of code which a user wants to perform. After the method has been declared, it is dependent on the user whether to define its implementation or not. Not writing any implementation, makes the method not to perform any task. However, when the user wants to perform certain tasks using method then it must write the statements for execution in the body of the method. The below syntax describes the basic structure of the method body :
Syntax :

<return_type> <method_name>(<parameter_list>)
{

     // Implementation of the method code goes here.....

}

 

Method Calling

Method Invocation or Method Calling is done when the user wants to execute the method. The method needs to be called for using its functionality. A method returns to the code that invoked it when:

Example : In the code below, a method named Sum() is called.




// C# program to illustrate
// method calling
using System;
namespace ConsoleApplication1 {
     
class Geeks {
 
    // Here Sum() method asks for two
    // parameters from the user and
    // calculates the sum of these
    // and finally returns the result.
    static int Sum(int x, int y)
    {
     
            // there are two local variables
            // 'a' and 'b' where 'a' is assigned
            // the value of parameter 'x' and
            // 'b' is assigned the value of
            // parameter 'y'
            int a = x;
            int b = y;
     
            // The local variable calculates
            // the sum of 'a' and 'b'
            // and returns the result
            // which is of 'int' type.
            int result = a + b;
     
            return result;
        }
 
    // Main Method
    static void Main(string[] args)
    {
        int a = 12;
        int b = 23;
 
        // Method Sum() is invoked and
        // the returned value is stored
        // in the local variable say 'c'
        int c = Sum(a, b);
         
        // Display Result
        Console.WriteLine("The Value of the sum is " + c);
    }
}
}

Output :  

The Value of the sum is 35

Method Parameters

There might be certain situations the user want to execute a method but sometimes that method requires some value inputs in order to execute and complete its tasks. These input values are known as Parameters in a computer language terms. Now, these parameters can be either int, long or float or double or char. However, it depends upon the user requirements. The methods in C# can be classified into different categories based on return type as well as input parameters. 
 




// C# program to illustrate method Without
// Parameters & Without Return Type
using System;
namespace ConsoleApplication2 {
class Geeks {
 
    // Here the method 'PrintSentence()'
    // neither takes any parameter nor
    // returns any value. It simply performs
    // the required operations and prints
    // the result within it.
    static void PrintSentence()
    {
         
        Console.WriteLine("No parameters and return type void");
    }
 
    // Main Method
    static void Main(string[] args)
    {
 
        // Method Invoking or Method calling
        PrintSentence();
    }
}
}

No parameters and return type void




// C# program to illustrate the method Without
// Parameters & With Return Value Type
using System;
namespace ConsoleApplication3 {
     
class Geeks {
 
    // This method takes no parameter,
    // however returns the result obtained
    static int sum()
    {
        int a = 78, b = 70, add;  
        add = a + b;
        return add; 
    }
 
    // Main Method
    static void Main(string[] args)
    {
         
        // Here the calling variable
        // is 'getresult'
        int getresult = sum();
 
        // Printing the value of
        // 'getresult' variable
        Console.WriteLine(getresult);
    }
}
}

148




// C# program to illustrate Method With
// Parameters & Without Return Value Type
using System;
namespace ConsoleApplication3 {
class Geeks {
         
    // This method take the side of
    // the square as a parameter and
    // after obtaining the result,
    // it simply print it without
    // returning anything..
    static void perimeter(int p)
    {
 
        // Displaying the perimeter
        // of the square
        Console.WriteLine("Perimeter of the Square is " + 4 * p);
    }
 
    // Main  Method
    static void Main(string[] args)
    {
 
        // side of square
        int p = 5;
 
        // Method invoking
        perimeter(p);
    }
}
}

Perimeter of the Square is 20




// C# program to illustrate Method With
// Parameters & With Return Value Type
using System;
namespace ConsoleApplication4 {
class Geeks {
     
    // This method asks a number from
    // the user and using that it
    // calculates the factorial
    // of it and returns the result
    static int factorial(int n)
    {
        int f = 1;
 
        // Method to calculate the
        // factorial of a number
        for (int i = 1; i<= n; i++)
        {
            f = f * i;
        }
 
        return f;
    }
 
    // Main Method
    static void Main(string[] args)
    {
        int p = 4;
 
        // displaying result by calling the function
        Console.WriteLine("Factorial is : " + factorial(p));
    }
}
}

Factorial is : 24

Advantages of using the Methods : 
There are many advantages of using methods. Some of them are listed below: 


Article Tags :
C#