Easy Tutorial
❮ Csharp Unsafe Codes Csharp Jagged Arrays ❯

A method is a block of statements organized together to perform a specific task. Every C# program has at least one class with a Main method.

To use a method, you need to:

Defining a Method in C

When defining a method, you are essentially declaring its structure. The syntax for defining a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}

Here are the elements of a method:

Example

The following code snippet shows a function FindMax that takes two integer values and returns the larger one. It has a public access modifier, so it can be accessed from outside the class using an instance of the class.

class NumberManipulator
{
   public int FindMax(int num1, int num2)
   {
      /* Local variable declaration */
      int result;

      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result;
   }
   ...
}

Calling a Method in C

You can call a method using its name. The following example demonstrates this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* Local variable declaration */
         int result;

         if (num1 > num2)
            result = num1;
         else
            result = num2;

         return result;
      }
      static void Main(string[] args)
      {
         /* Local variable definition */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         // Calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is: {0}", ret );
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Max value is: 200

You can also call public methods of other classes from another class using an instance of that class. For example, the FindMax method belongs to the NumberManipulator class and can be called from another class Test.

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* Local variable declaration */
         int result;

         if (num1 > num2)
            result = num1;
         else
            result = num2;

         return result;
      }
   }
   class Test
   {
      static void Main(string[] args)
      {
         /* Local variable definition */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         // Calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is: {0}", ret );
         Console.ReadLine();
      }
   }
}
static void Main(string[] args)
{
    /* Local variable definition */
    int a = 100;
    int b = 200;
    int ret;
    NumberManipulator n = new NumberManipulator();
    // Calling the FindMax method
    ret = n.FindMax(a, b);
    Console.WriteLine("Max value is: {0}", ret);
    Console.ReadLine();
}

When the above code is compiled and executed, it produces the following result:

Max value is: 200

Recursive Method Call

A method can call itself. This is called recursion. The following example uses a recursive function to calculate the factorial of a number:

Example

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* Local variable definition */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }

        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            // Calling the factorial method
            Console.WriteLine("Factorial of 6 is: {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is: {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is: {0}", n.factorial(8));
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Parameter Passing

When you call a method with parameters, you need to pass the parameters to the method. In C#, there are three ways to pass parameters to a method:

Method Description
Value Parameters This method copies the actual value of an argument into the formal parameter of the function. This means that changes made to the parameter inside the function have no effect on the argument.
Reference Parameters This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
Output Parameters This method can return multiple values.

Passing Parameters by Value

This is the default mechanism for passing parameters. In this case, when a method is called, a new storage location is created for each value parameter.

The value of the actual parameter is copied into the formal parameter. The actual and formal parameters then reference different memory locations. So, changes made to the parameter inside the function do not affect the argument, thus ensuring the safety of the actual parameter's data. The following example illustrates this concept:

Example

using System;
namespace CalculatorApplication
{
    class NumberManipulator
    {
        public void swap(int x, int y)
        {
            int temp;

            temp = x; /* Save the value of x */
            x = y;    /* Assign y to x */
            y = temp; /* Assign temp to y */
        }

        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            /* Local variable definition */
            int a = 100;
            int b = 200;

            Console.WriteLine("Before swap, value of a : {0}", a);
            Console.WriteLine("Before swap, value of b : {0}", b);

            /* Calling a function to swap the values */
            n.swap(a, b);

            Console.WriteLine("After swap, value of a : {0}", a);
            Console.WriteLine("After swap, value of b : {0}", b);

            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
NumberManipulator n = new NumberManipulator();
/* Local variable definition */
int a = 100;
int b = 200;

Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);

/* Call the function to swap values */
n.swap(a, b);

Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

The result shows that the values have not changed even after they were altered inside the function.

Passing Parameters by Reference

A reference parameter is a reference to the memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are provided to the method.

In C#, you declare reference parameters using the ref keyword. The following example demonstrates this:

Example

using System;
namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void swap(ref int x, ref int y)
      {
         int temp;

         temp = x; /* Save the value of x */
         x = y;    /* Put y into x */
         y = temp; /* Put temp into y */
      }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* Local variable definition */
         int a = 100;
         int b = 200;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* Call the function to swap values */
         n.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);

         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

The result shows that the values inside the swap function changed and this change is reflected in the Main function.

Passing Parameters by Output

The return statement can be used to return only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are similar to reference parameters, except that they transfer data out of the method.

The following example demonstrates this:

Example

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void getValue(out int x)
      {
         int temp = 5;
         x = temp;
      }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* Local variable definition */
         int a = 100;

         Console.WriteLine("Before method call, value of a : {0}", a);

         /* Calling a function to get the value */
         n.getValue(out a);

         Console.WriteLine("After method call, value of a : {0}", a);
         Console.ReadLine();
      }
   }
}
Console.WriteLine("Before method call, the value of a: {0}", a);

/* Call the function to get the value */
n.getValue(out a);

Console.WriteLine("After method call, the value of a: {0}", a);
Console.ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:

Before method call, the value of a: 100
After method call, the value of a: 5

Variables provided to output parameters do not need to be assigned a value. Output parameters are particularly useful when you need to return values from a method without specifying an initial value for the parameter. Look at the following example to understand this:

Example

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void getValues(out int x, out int y)
      {
          Console.WriteLine("Please enter the first value: ");
          x = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine("Please enter the second value: ");
          y = Convert.ToInt32(Console.ReadLine());
      }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* Local variable definition */
         int a, b;

         /* Call the function to get the values */
         n.getValues(out a, out b);

         Console.WriteLine("After method call, the value of a: {0}", a);
         Console.WriteLine("After method call, the value of b: {0}", b);
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result (depending on user input):

Please enter the first value:
7
Please enter the second value:
8
After method call, the value of a: 7
After method call, the value of b: 8
❮ Csharp Unsafe Codes Csharp Jagged Arrays ❯