C# Methods

  • A C# method is a block of statements grouped together to realize a certain function.
  • C# methods, like all the OOP languages, are similar as the procedural programming functions which are called to run.
  • All the instructions in C# are running in a method of a class or a struct.
  • The common language runtime (CLR) always calls "Main" method as an entry point of running the program.
  • C# methods can have several parameters or no parameter.

The syntax to define a method as follow.

[<Access Modifier>] <Return Data Type> <Method Name>([Parameter List])
{
    [C# statements;]
    [return [<Return Data Type>];]
}

The syntax of parameter list is like:

[<Data Type 1> <Parameter Name 1>,] [<Data Type 2> <Parameter Name 2>,] [..., <Data Type n> <Parameter Name n>]

Syntax Explanation:

  • <Access Modifier> can be public, private, internal, protected or protected internal. It can be omitted if it is internal.
  • <Return Data Type> is the returned data type after the method is called. If it is void, nothing will be returned.
  • <Method Name> is the name of the method which can be defined following the variable naming rules.
  • [Parameter List] stands for 0 to n parameters. The parameters are enclosed in parentheses and separated by commas.
  • Each parameter includes data type and parameter name. An empty parenthese in a method means no parameter.
  • [C# statements;] stands for 0 to n C# statements.
  • [return [<Return Data Type>];] stands for an option of using return statement. If the data type is void, no <Return Data Type> is needed. Otherwise, you will have to put return statement where the method is finished calling and the <Return Data Type> must be matched each other (See the syntax in red).

The syntax to call a method is shown below.

[<Access Modifier>] <Return Data Type> <Method Name>([Argument List]);
  • The syntax of calling a method is the same as that of defining a method except the body part is changed to a semicolon and the parameter list is changed to argument list.
  • The argument list is the real data transferred to the counterparts of the parameter list with the compatible data type.
  • The argument name can be different from the corresponding parameter name.

Example 01-43-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
class Test
{
    static void Main(string[] args)
    {
        Test t = new Test();
        t.method1();
        t.method2();
		
        Console.Read();
    }

    public void method1(){
        Console.WriteLine("Method 1 Output.");		
    }

    public void method2(){
        method1();
        Console.WriteLine("Method 2 Output.");
    }
}

Output

Method 1 Output.
Method 1 Output.
Method 2 Output.

Explanation

  • Line 2: Start defining a class Test.
  • Line 4: Define a Main method.
  • Line 6: Create an instance of class Test and assign it to the variable t.
  • Line 7: Run method1 to output "Method 1 Output.".
  • Line 8: Run method2.
  • Line 13-15: Define method1 with one statement to output the string.
  • Line 17-20: Define method2. Firstly call method1 to output "Method 1 Output." and output "Method 2 Output."

In the above example, method1 is call in method2. This is the key to develop object-oriented programs. A big whole project can be separated into small pieces of code spreading in many methods of classes. Each method only realizes a small function and can be invoked by other methods. All these classes with fields and methods compose a program.

Example 01-43-02

In the following example, we'll realize add and minus function with parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;

namespace TestMethod
{
    class Calculation
    {
        public int add( int a, int b)
        {
            return a + b;
        }

        public int minus( int a, int b)
        {
            return a - b;
        }
    }
	
    class TestHouse
    {
        static void Main(string[] args)
        {
            Calculation c = new  Calculation();
			
            Console.WriteLine("789 + 456 = {0}", c.add(789,456));
            Console.WriteLine("789 - 456 = {0}", c.minus(789,456));
            Console.Read();
        }
    }
}

Output

789 + 456 = 1245
789 - 456 = 333
  • Line 5-16: Define a class Calculation.
  • Line 7-10: Define a add method with return data type int.
  • Line 9: Use "return" statement to return the result of a + b. The result is int type which meets the requirement of returned data type.
  • Line 9: The field isDetached is declared as bool with default value false.
  • Line 12-15: Define a minus method with return data type int.
  • Line 14: Use "return" statement to return the result of a - b.
  • Line 20: The program starts with Main method.
  • Line 22: Create an object and assign it to c.
  • Line 24-25: Output the add and minus result by calling the 2 methods.