C# methods are reusable code blocks. By calling a c# method, all of the code in the method will be executed.

Methods should start with a lowercase character and only contain alphabetic characters.
A method can take one or more parameters which can be used in the code block.

Methods in C#

Example

The method below can be called as many times as you want: a method is reusable code.
Methods can also return output, this output can then be used in the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;

namespace CalculatorApplication {
class Example {
public void hello(string x1) {
Console.WriteLine("Hello {0}", x1 );
}

static void Main(string[] args) {
hello("Alice");
Console.ReadLine();
}
}
}

The method hello above is called with a parameter and without.
Sometimes parameters are necessary for your codeblock, but at times they are not.

The parameter in this example is x1, which is given a value outside the method.

Return valule

A value inside a csharp method only exists there (local scope). It can be given to the program with the return statement, return x1. That then needs to be saved in an output variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace CalculatorApplication {
class Example {
public float multiply(float x1, float x2) {
float c = x1 * x2;
return c;
}

static void Main(string[] args) {
float output = 0;
output = multiply(2,4);
Console.WriteLine("Output {0}",output);
Console.ReadLine();
}
}
}

Exercises

  1. Create a method that sums two numbers
  2. Create a method that calls another method.