Methods are Blocks of Code
Have you ever heard of functions, procedures, or subroutines? These are blocks of code that perform a specific task. In C# we call them methods. Methods break our code down into reusable chunks. They are like little “machines” that we can call over and over again to perform a task.
Little Machines
Think of the tools and machines you use in your life to perform a repetitive task, or to keep your life organized. You load dirty clothes and soap into a washing machine, set the controls, and tell it to start. It runs through its washing processes and changes your clothes from dirty to clean (and wet). You set your alarm clock to wake you at 6:00 am. Its job is to sound the alarm when it's time. You pick up a calculator to perform mathematical calculations. You give it some numbers and a mathematical operator, and it returns the result.
We all use machines in real life, and guess what? We’ve already been using them in code, too! Now let’s learn how to create our own.
Where Do I Live?
Methods live in a class. The Main()
method in our Program class is a method. The WriteLine()
method is a member of the Console class.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args) // Main is a method
{
Console.WriteLine("Hello World!"); // WriteLine is a method, too
}
}
}
We will begin by writing methods in the Program class. When we learn how to create our own unique classes, we will add methods here too.
Syntax. Gesundheit.
Here is a simple method called SayHello()
that prints the message “Hello!” to the console. Let’s break it down into its components and examine its “syntax”, or the rules that define the order of key words and characters:
public void SayHello()
{
Console.WriteLine(“Hello!”);
}
-
Access Modifier In this example,
public
is the access modifier. It sets the access level for the method. A public method is accessible by all classes, which means we can call this method from all other classes. Specifying an access modifier is optional. If you do not specify an access modifier for a method, it is assigned private access by default. A private method can only be accessed within the class in which it is written. -
Return Type In this example,
void
is a placeholder for the method's return type. TheSayHello()
method prints "Hello!" to the console, but it does not return a separate message back to the caller. Even if the method does not return any data, specifying a method's return type is required. -
Method Name
SayHello
is the name of our method above. A method's name should clearly describe its purpose. It is written in Pascal case, which is the proper naming convention for methods in C#. Notice how the first letter of each word in the method's name is capitalized. Methods must have a name. -
Parameter List Parentheses always follow the name of a method. The parentheses contain the method's parameter list. In the example above, we have no parameters.
-
Method Body A method's parameter list is always followed by a set of curly braces {} which surround the method's body. The body contains all the code that will be executed when a method is run. When
SayHello()
is executed it will print "Hello!" to the console.
More Syntax.
Let’s create a simple calculator method that adds 2 numbers. Here is what that may look like:
int AddNumbers(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
-
Access Modifier In this example, the access modifier is not explicitly named. Remember, specifying an access modifier is optional. By default it has been assigned the private accessibility level. A private method can only be accessed, or called, from the class in which it is written.
-
Return Type In this example,
int
has been defined as the method's return type. Because we specified a return type, theAddNumbers()
method must return data of typeint
to the caller of the method. It does this by using thereturn
keyword, followed by an expression that evaluates to anint
. The return type must match the data that is returned from the method body. -
Method Name
AddNumbers
is the name of our method above. A method's name should clearly describe its purpose and be written in Pascal case. -
Parameter List The parentheses of this method contains a parameter list consisting of two parameters. Parameters are variables that the method needs to do its work. In the case of the
AddNumbers()
method, it needs to know what numbers it is adding! All parameters are defined by providing a data type and a name. In our example, the first parameter is defined as typeint
and we have given it the namefirstNumber
. The second parameter is also defined as typeint
and we have given it the namesecondNumber
. You can define a method with up to 65,500 parameters! But in order to keep your code clean and easy to read, you should use as few parameters as possible. -
Method Body A method's parameter list is always followed by a set of curly braces {} which encapsulate the method's body. The body contains all the code that will be executed when a method is run. When
AddNumbers()
is executed it will add the value offirstNumber
to the value ofsecondNumber
, and return that sum to the caller of the method with thereturn
keyword.
Ring, Ring, Are you There?
Let’s talk about calling methods. Earlier we defined a SayHello()
method, but the method does not do anything until we call it. Below is the syntax for calling the SayHello()
method:
SayHello();
That was pretty simple, but let’s break it down even further.
To call a method, first we reference the name of the method, “SayHello”, followed by any parameters that it needs. If you recall, SayHello()
doesn’t take any parameters, therefore the parentheses are empty. In addition, the method does not return any information to the caller. Remember the void
keyword? We simply call the SayHello()
method as written above, and it does the work of printing “Hello” to the console. Done!
Is Anybody Out There?
We also created an AddNumbers()
method, but again, the method does not do anything for us until we call it. It's like a calculator that sits in a drawer. It doesn’t do any work until we pull it out and use it.
Before we talk about how to call AddNumbers()
within our code, let’s revisit our real washing machine, alarm clock, and calculator. In order for our washing machine to do its work, we need to give it a few things. Before we hit the start button, we give it soap, dirty clothes, and set the wash cycle. Our alarm clock needs to know what time we want to get up. Before we can use our calculator to add numbers, we need to type those numbers into the calculator, along with the addition operator and the equals sign, and then our calculator returns the answer to us.
In our "machine" analogy, the information we give to our machines are the arguments. The work the machine does is part of its body. The machine may or may not return information to us. And we are the caller, the one who “starts” the machine.
Let’s call our AddNumbers()
method. This is the syntax for calling this method in C#:
int sumOfTwoNumbers = AddNumbers(20, 7);
To call AddNumbers()
we reference the name of the method, "AddNumbers”, and give it values that match the method’s parameter list. Those values are called arguments. The first parameter required by our AddNumbers()
method is an int
. We satisfied that requirement by passing the number 20 in as the first argument. The second parameter required by our AddNumbers()
method is also an int
. We satisfied that requirement by passing the number 7 in as the second argument.
Then what happens? The AddNumbers “machine” does its work. Recall the body of the AddNumbers()
method. In the body, the 2 parameters are added together and the sum is returned to the caller. We are the caller! But how do we, the “caller”, capture the return value? In a real calculator we capture it by looking at the answer displayed on the calculator screen. In our AddNumbers()
method above, we capture it in a variable of type int
, named sumOfTwoNumbers
.
To better understand how this works, read the code on the right of the equals sign first. First the AddNumbers()
method is called. After our AddNumbers()
method executes, it returns the value 27. Then 27 is assigned to the variable named sumOfTwoNumbers
.
Did you notice that the return type of our method -> int
,
...matches the data type of our return statement -> firstNumber + secondNumber
,
...which also matches the variable type that captures our return value -> sumOfTwoNumbers
?
This is not accidental, it is necessary! Our method and the caller of the method are in communication with each other. Therefore, we must clearly define the type of information that is passed in and out of each method.
Method Overloading
It is possible to define more than one method with the same name. This is called Method Overloading. You can use method overloading to perform the same task, but on different amounts or types of incoming data. Overloaded methods can provide slightly different implementation in the method body.
In order to overload a method, the method’s signature must be unique. The signature is the combination of the method name and the number, types, and order of the method’s parameters.
For example, the methods below have the same signatures. This is not permitted in C# and will create a syntax error. Even though the body of the methods are different, C# views these methods as the same. The return type is not part of the method signature in C#.
public void SayHello(string name) // This parameter list contains 1 string
{
Console.Log(“Hello, “ + name);
}
public void SayHello(string customerName) // This parameter list also contains 1 string
{
Console.log(“Welcome “ + customerName);
}
The following methods are examples of the correct use of Method Overloading. The names of the methods are the same, but the signatures are different.
public int AddNumbers(int firstNumber, int secondNumber) // This parameter list contains 2 ints
{
return firstNumber + secondNumber;
}
public int AddNumbers(int firstNumber, int secondNumber, int thirdNumber) // This parameter list contains 3 ints
{
return firstNumber + secondNumber + thirdNumber;
}
public double AddNumbers(double firstNumber, double secondNumber) // This parameter list contains 2 doubles
{
return firstNumber + secondNumber;
}
public void AddNumbers(string name, double firstNumber, double secondNumber) // This parameter list contains 1 string and 2 doubles
{
double sum = firstNumber + secondNumber;
Console.WriteLine(“Hello, “ + name);
Console.WriteLine(“The sum of “ + firstNumber + “ and “ + secondNumber + “ is “ + sum);
}