C # method


Release date:2023-08-26 Update date:2023-10-13 Editor:admin View counts:289

Label:

C # method

One way is to organize some related statements together to perform a block of statements for a task. Every C# program has at least one with Main class.

To use a method, you need to:

  • Definition method

  • Call method

Define method in C #

When you define a method, you are basically declaring the elements of its structure. In C #, the syntax for defining a method is as follows:

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

Here are the elements of the method:

  • Access Specifier sccess modifier, which determines the visibility of a variable or method to another class.

  • Return type returns the type, and a method can return a value the returntype is the data type of the value returned by the method. If the method does not return any value, the return type is void .

  • Method name method name, which is a unique identifier and is case-sensitive It cannot be the same as other identifiers declared in the class.

  • Parameter list a list of parameters, enclosed in parentheses, that are used to pass and receive data for the method The parameter list refers to the parameter type, order, and quantity of the method. Parameters are optional, that is, a method may not contain parameters.

  • Method body: method body contains the set of instructions needed to complete the task.

Example

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

Example

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 method in C #

You can use the method name to call the method. The following example demonstrates this:

Example

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)
      {
         /* Definition of Local Variables */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();
         //call FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("The maximum value is: {0}", ret );
         Console.ReadLine();
      }
   }
}

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

The maximum value is: 200

You can also use an instance of a class to call public methods of another class from another class. For example, the method FindMax belong to NumberManipulator class, you can get it from another class Test useit in the middle.

Example

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)
        {
            /* Definition of Local Variables */
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator();
            //call FindMax method
            ret = n.FindMax(a, b);
            Console.WriteLine("The maximum value is: {0}", ret );
            Console.ReadLine();
        }
    }
}

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

The maximum value is: 200

Recursive method call

A method can be called by 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)
        {
            /* Definition of Local Variables */
            int result;
            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }

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

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

The factorial of 6 is: 720
The factorial of 7 is: 5040
The factorial of 8 is: 40320

Parameter transfer

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

Mode

Description

Value parameter

In this way, the actual value of the parameter is copied to the formal parameter of the function, and the argument and the parameter use two different values in memory. In this case, when the value of the parameter changes, it will not affect the value of the parameter, thus ensuring the security of the parameter data.

Reference parameter

In this way, a reference to the memory location of the parameter is copied to the formal parameter. This means that when the value of the parameter changes, it also changes the value of the parameter.

Output parameter

Multiple values can be returned in this way.

Pass parameters by value

This is the default way to pass parameters. In this way, when a method is called, a new storage location is created for each value parameter.

The value of the actual parameter is copied to the parameter, which uses twodifferent values in memory. Therefore, when the value of the parameter changes, it will not affect the value of the parameter, thus ensuring the security of the parameter data. The following example demonstrates 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();
         /* Definition of Local Variables */
         int a = 100;
         int b = 200;

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

         /* Calling functions to exchange values */
         n.swap(a, b);

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

         Console.ReadLine();
      }
   }
}

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

Before swapping, the value of a is: 100
Before exchange, the value of b is 200
After exchange, the value of a is 100
After exchange, the value of b is 200

The results show that even if the value is changed within the function, the value does not change at all.

Pass parameters by reference

A reference parameter is a reference to the memory location of a variable. When parameters are passed by reference, unlike value parameters, it does not create a new storage location for those parameters. The reference parameter represents the same memory location as the actual parameter provided to the method.

In C #, use the ref keyword declares reference parameters. 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;    /* Assign y to x */
         y = temp; /* Assign temp to y*/
       }

      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* Definition of Local Variables */
         int a = 100;
         int b = 200;
         Console.WriteLine("Before swapping, the value of a: {0}", a);
         Console.WriteLine("Before swapping, the value of b: {0}", b);
         /* Calling functions to exchange values */
         n.swap(ref a, ref b);
         Console.WriteLine("After exchange, the value of a: {0}", a);
         Console.WriteLine("After exchange, the value of b: {0}", b);

         Console.ReadLine();
      }
   }
}

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

Before swapping, the value of a is: 100
Before exchange, the value of b is 200
After exchange, the value of a is 200
After exchange, the value of b is: 100

The results show that swap value within the function has changed, and this change can be found in the Main is reflected in the function.

Pass parameters by output

return statement can be used to return only one value from a function. However, you can use output parameters to return two values from the function. The output parameter assigns the data output by the method to itself, and is similar to the reference parameter in other aspects.

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();
         /* Definition of Local Variables */
         int a = 100;

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

         /* Calling functions to obtain values*/
         n.getValue(out a);
         Console.WriteLine("After the method call, the value of a: {0}", a);
         Console.ReadLine();
      }
   }
}

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

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

Variables supplied to output parameters do not need to be assigned. Output parameters are especially useful when you need to return a value from a method where a parameter does not specify an initial value. See 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();
         /* Definition of Local Variables */
         int a , b;

         /*Calling functions to obtain values */
         n.getValues(out a, out b);
         Console.WriteLine("After the method call, the value of a: {0}", a);
         Console.WriteLine("After the method call, the value of b: {0}", b);
         Console.ReadLine();
      }
   }
}

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

Please enter the first value: 7
Please enter the second value: 8
After the method call, the value of a is: 7
After the method call, the value of b is: 8

Powered by TorCMS (https://github.com/bukun/TorCMS).