Methods or Functions

Method is a set of code which only runs when it is called. Methods are also known as Functions. Method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method. In C#, every executed instruction is performed in the context of a method. We can pass data, known as parameters, into a method(We going to study this in detail in upcoming articles).

So far we written all our codes inside { and } of static void main(), where main is nothing but a Method. We can create our own method. A method is defined with the name of the method, followed by parentheses().

CODE

EG 1 . Creating a simple addition method and calling it in main method.

//Our Program will work fine even without string[] args, so from next code onwards we going to remove that.
static void Main(string[] args) {
    Addition(); // This is called as Calling a method or Invoking a Method
}
//We not yet studied what static void keywords are, we going to study those in upcoming articles. For now copy paste main method and only change method name.
static void Addition() {
    int a = 5;
    int b = 6;
    int c = a + b;
    Console.WriteLine(c);
}



EG 2 . Creating a multiplication table method and invoking inside main method.

static void Main() {
    MultiplicationTable();
}
static void MultiplicationTable() {
    int tableNumber = 17;
    int limit = 20;
    for (int i=1; i <= limit; i++) {
        Console.WriteLine(tableNumber+" * "+i+" = "+(tableNumber*i));
    }
}




(Click Here, For more exercises)