Fundamentals of Computer Programming with C# HTML version
Chapter 9. Methods
In This Chapter
In this chapter we will get more familiar with what methods are and why we
need to use them. The reader will be shown how to declare methods, what
parameters are and what a method’s signature is, how to call a method,
how to pass arguments of methods and how methods return values. At the
end of this chapter we will know how to create our own method and how to
use (invoke) it whenever necessary. Eventually, we will suggest some good
practices in working with methods. The content of this chapter accompanied
by detailed examples and exercises that will help the reader practice the
Subroutines in Programming
To solve a certain task, especially if it is a complex one, we apply the method
that ancient Romans did “divide and conquer”. According to this principle,
the problem we solve must be divided into small subproblems. Taken
separately they are well defined and easy to be resolved compared to the
original problem. At the end by finding solutions for all the small problems we
solve the complex one.
Using the same analogy, whenever we write a software program we aim to
solve particular task. To do it in an efficient and “easy-to-make” way we use
the same mentioned above principle “divide and conquer”. We separate the
given task into smaller tasks, then develop solutions for them and put them
together into one program. Those smaller tasks we call subroutines.
In some other programming languages subroutines can be named as
functions or procedures. In C#, they are called methods.
What Is a "Method"?
A method is a basic part of a program. It can solve a certain problem,
eventually take parameters and return a result.
A method represents all data conversion a program does, to resolve a
particular task. Methods consist of the program’s logic. Moreover they are
the place where the “real job” is done. That is why methods can be taken as a
base unit for the whole program. This on the other hand, gives us the
opportunity, by using a simple block, to build bigger programs, which resolve
more complex and sophisticated problems. Below is a simple example of a
method that calculates rectangle’s area: