Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The C#method


May 11, 2021 C#


Table of contents


The C#method

One approach is to organize some related statements together to execute a block of statements for a task. Each C#program has at least one class with the Main method.

To use one method, you need to:

  • Define the method
  • The method is called

Define the method in C#

When defining a method, it is essentially an element that declares its structure. In C#, the syntax for defining the method is as follows:

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

Here are the elements of the method:

  • Access Specifier: Access modifiers, which determine the visibility of a variable or method to another class.
  • Return type: Return type, a method can return a value. T he return type 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: The method name is a unique identifier and 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 from a method. A list of parameters is the type, order, and number of parameters for a method. Arguments are optional, that is, a method may not contain parameters.
  • Method body: Method body, which contains the set of instructions required to complete the task.

The following snippet shows a function, FindMax, that accepts two integer values and returns the larger values in both. It has a public access modifier, so it can be accessed from outside the class using instances of the class.

class NumberManipulator
{
   public int FindMax(int num1, int num2)
   {
      /* 局部变量声明 */
      int result;

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

      return result;
   }
   ...
}

The method is called in C#

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

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* 局部变量声明 */
         int result;

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

         return result;
      }
      static void Main(string[] args)
      {
         /* 局部变量定义 */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //调用 FindMax 方法
         ret = n.FindMax(a, b);
         Console.WriteLine("最大值是: {0}", ret );
         Console.ReadLine();
      }
   }
}

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

最大值是: 200

You can also use an instance of a class to call a public method of another class from another class. For example, the method FindMax belongs to the NumberManipulator class, which you can call from another class Test.

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int FindMax(int num1, int num2)
        {
            /* 局部变量声明 */
            int result;

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

            return result;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            /* 局部变量定义 */
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator();
            //调用 FindMax 方法
            ret = n.FindMax(a, b);
            Console.WriteLine("最大值是: {0}", ret );
            Console.ReadLine();

        }
    }
}

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

最大值是: 200

Recursive method calls

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

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* 局部变量定义 */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            //调用 factorial 方法
            Console.WriteLine("6 的阶乘是: {0}", n.factorial(6));
            Console.WriteLine("7 的阶乘是: {0}", n.factorial(7));
            Console.WriteLine("8 的阶乘是: {0}", n.factorial(8));
            Console.ReadLine();

        }
    }
}

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

6 的阶乘是: 720
7 的阶乘是: 5040
8 的阶乘是: 40320

The argument is passed

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

Way describe
Value parameters This method of copying the actual value of the parameters to the formal parameters of the function, the arguments, and shape are used by the values in two different memory.In this case, when the value of the parameter is changed, the value of the arctic is not affected, thereby ensuring the security of the unintended data.
Quote parameter This method of copying the reference parameters of the memory location of the parameters.This means that when the value of the parameter changes, the value of the arctic is also changed.
Output parameters This approach can return multiple values.

Pass arguments by value

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

The values of the actual parameters are copied to the parameters, which use two values in different memory. T herefore, when the value of the parameter changes, the value of the parameter is not affected, thus ensuring the security of the parameter data. The following example demonstrates this concept:

using System;

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

            temp = x; /* 保存 x 的值 */
            x = y;    /* 把 y 赋值给 x */
            y = temp; /* 把 temp 赋值给 y */
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            /* 局部变量定义 */
            int a = 100;
            int b = 200;

            Console.WriteLine("在交换之前,a 的值: {0}", a);
            Console.WriteLine("在交换之前,b 的值: {0}", b);

            /* 调用函数来交换值 */
            n.swap(a, b);

            Console.WriteLine("在交换之后,a 的值: {0}", a);
            Console.WriteLine("在交换之后,b 的值: {0}", b);
 
            Console.ReadLine();
        }
    }
}

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

在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:100
在交换之后,b 的值: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 argument is a reference to the memory location of a variable. W hen parameters are passed by reference, unlike value parameters, it does not create a new storage location for those parameters. Reference parameters represent the same memory location as the actual parameters provided to the method.

In C#, use the ref keyword to declare a reference parameter. The following example demonstrates this:

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

         temp = x; /* 保存 x 的值 */
         x = y;    /* 把 y 赋值给 x */
         y = temp; /* 把 temp 赋值给 y */
       }
   
      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* 局部变量定义 */
         int a = 100;
         int b = 200;

         Console.WriteLine("在交换之前,a 的值: {0}", a);
         Console.WriteLine("在交换之前,b 的值: {0}", b);

         /* 调用函数来交换值 */
         n.swap(ref a, ref b);

         Console.WriteLine("在交换之后,a 的值: {0}", a);
         Console.WriteLine("在交换之后,b 的值: {0}", b);
 
         Console.ReadLine();

      }
   }
}

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

在交换之前,a 的值:100
在交换之前,b 的值:200
在交换之后,a 的值:200
在交换之后,b 的值:100

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

Pass parameters by output

The return statement can be used to return only one value from a function. H owever, you can use the output parameter to return two values from the function. The output parameters assign the data output of the method to themselves, and other aspects are similar to the reference parameters.

The following example demonstrates this:

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();
         /* 局部变量定义 */
         int a = 100;
         
         Console.WriteLine("在方法调用之前,a 的值: {0}", a);
         
         /* 调用函数来获取值 */
         n.getValue(out a);

         Console.WriteLine("在方法调用之后,a 的值: {0}", a);
         Console.ReadLine();

      }
   }
}

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

在方法调用之前,a 的值: 100
在方法调用之后,a 的值: 5

Variables provided to the output parameters do not need to be assigned. O utput parameters are especially useful when you need to return a value from a method where the argument does not specify an initial value. Take a look at the following example to understand this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void getValues(out int x, out int y )
      {
          Console.WriteLine("请输入第一个值: ");
          x = Convert.ToInt32(Console.ReadLine());
          Console.WriteLine("请输入第二个值: ");
          y = Convert.ToInt32(Console.ReadLine());
      }
   
      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         /* 局部变量定义 */
         int a , b;
         
         /* 调用函数来获取值 */
         n.getValues(out a, out b);

         Console.WriteLine("在方法调用之后,a 的值: {0}", a);
         Console.WriteLine("在方法调用之后,b 的值: {0}", b);
         Console.ReadLine();
      }
   }
}

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

请输入第一个值:
7
请输入第二个值:
8
在方法调用之后,a 的值: 7
在方法调用之后,b 的值: 8