This is your first visit inside The Matrix. Welcome!

The Matrix has you…

This place will take you into the mirage of learning C# programming language, without any previous coding experience being required

Follow the White Rabbit…█

Close
Tuesday, July 17, 2018 07:47

Methods and functions declaration

Methods and functions declarations is actually a three step process: declaration, implementation, call  of our method or function.

  • Declaration is the process of writing the method type, name and eventual parameters, so the program can successfully identify it.
  • Implementation of a method is writing the actual code that will be executed when the method is executed.
  • Call is the process of invoking the already declared and implemented method from some part of the program, where a problem that the method should solve, must be solved.

Declaration of a method cannot be done wherever we want. Although we haven’t yet learned about classes, we are going to mention them here because methods can only be declared inside the block of a class. As you have already seen in some of our previous examples, our Main method was declared inside the curly brackets of a class (the body of that class). So, for now, imagine a class like a structure defined by a name, having a body delimited by opening and closing curly brackets. In this context, a method declaration would look like this:

In the above example, we have declared a class named HelloWorld, and inside its block, a method called GreetTheWorld. Now, this method is only declared, but it doesn’t do anything, since its body contains no code. This is done in the implementation of the method:

By placing the two instructions inside the body of our method, we have “implemented” it, meaning, we have given our method something to do when we will call it. Speaking of, even if we declare and implement our method, it still doesn’t do anything by itself. This is where a method call comes useful. In order for our method to run the code inside its block, we need to first call our method:

In the above example, we have declared and implemented our method. Aside of that, you can notice a second method which we used in a lot of our previous lessons, called Main() (this is the first method that executes when a console program is started). Inside the block of our Main() method, we called our second method, GreetTheWorld().

We will describe these aspects in separate future lessons, for now you just have to know that a method can be declared, implemented and called.

Function declarations are somehow identical to methods declarations, with the only difference that they must return a value, like we explained in the previous lesson. Lets consider the following example:

Comments

comments

Tags: , , ,

Leave a Reply