Latest web development tutorials

C # method

One way is to put some relevant statements grouped together for a block of statements to perform the task. Every program has at least a C # class with a Main method.

To use a method, you need:

  • Definition method
  • Call the method

C # method as defined in

When defining a method, fundamentally speaking, it is in its element structure declaration. In C #, the syntax definition method is as follows:

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

The following are the individual elements of:

  • Access Specifier: access modifier, the decision variables or method for another class visibility.
  • Return type: return type, a method can return a value.The return type is the data type of the value returned by the method. If the method does not return any values, the return type isvoid.
  • Method name: the method name, is a unique identifier, and is case sensitive.It can not be the same as other identifier class declaration.
  • Parameter list: the list of parameters, enclosed in parentheses, the parameter is used for data transmission and receiving method.Parameter type parameter list refers to the method, the order and quantity. Parameter is optional, that is to say, a method may not contain parameters.
  • Method body: method body, including the need to complete tasks instruction set.

Examples

The following code fragment shows a functionFindMax,which accepts two integer values, and returns the larger of two values. It has a public access modifier, so it can be accessed using the instance of the class from outside the class.

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

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

      return result;
   }
   ...
}

Call methods in C #

You can use the name of the calling method. The following example illustrates this point:

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 definitions * /
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator ();

         // Call FindMax method ret = n.FindMax (a, b);
         Console.WriteLine ( "Max 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 other types of public methods class instance called from another class. For example, the methodFindMaxbelongNumberManipulatorclass, you can call it from another classTestin.

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 definitions * /
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator ();
            // Call FindMax method ret = n.FindMax (a, b);
            Console.WriteLine ( "Max is: {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 the self. This is calledrecursion.The following example uses a recursive function to calculate the factorial of a number:

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial (int num)
        {
            / * Local variable definitions * /
            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 the factorial method Console.WriteLine ( "6 factorial is: {0}", n.factorial (6));
            Console.WriteLine ( "7 factorial is: {0}", n.factorial (7));
            Console.WriteLine ( "8 factorial is: {0}", n.factorial (8));
            Console.ReadLine ();

        }
    }
}

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

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

Parameter passing

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 the method:

方式描述
值参数这种方式复制参数的实际值给函数的形式参数,实参和形参使用的是两个不同内存中的值。在这种情况下,当形参的值发生改变时,不会影响实参的值,从而保证了实参数据的安全。
引用参数这种方式复制参数的内存位置的引用给形式参数。这意味着,当形参的值发生改变时,同时也改变实参的值。
输出参数这种方式可以返回多个值。

Passing parameters by value

This is the default parameter passing. In this way, when you call a method that creates a new storage location for each parameter.

The actual parameter value is copied to parameters, arguments and parameters used in two different memory value. So, when the parameter value changes will not affect the value of the argument, thus ensuring the real parameter data security. The following example illustrates 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 showed that, even within the function changes the value, the value of any change had happened.

Pass parameters by reference

Reference parameter isa reference to the variable memory location.When the parameters passed by reference, with the value of the parameter is different it is that it does not create a new storage location for these parameters. Reference parameter represents the actual parameter to the method has the same memory location.

In C #, using theref keyword to declare a reference parameter.The following example illustrates this point:

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; / * y is assigned to the x * /
         y = temp; / * the temp assignment to y * /
       }
   
      static void Main (string [] args)
      {
         NumberManipulator n = new NumberManipulator ();
         / * Local variable definitions * /
         int a = 100;
         int b = 200;

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

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

         Console.WriteLine ( "After an exchange, a value of: {0}", a);
         Console.WriteLine ( "After an exchange, b values: {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 showed that the value of theswapfunction within the change, and this change can be reflected inthe Mainfunction.

Passing parameters by Output

return statement can be used only to return a value from a function. However, you can use theoutput parameter to return two values from functions.Data output parameter output method will assign their own, and other similar reference parameters.

The following example illustrates this point:

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

Supplied to the output parameter variables does not require the assignment. When you need to return a value from the initial value of a parameter is not specified in the method, the output parameter is particularly useful. Consider 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 result (depending on user input):

Please enter a value:
7
Please enter the second value:
8
After the method call, a value: 7
After the method call, b values: 8