I could tell that Noname was continuously getting better. I started to notice small quirks occurring around me: doors opening as I walked towards them, elevators whisking me to the correct floor before I even touched the button, and so on - things I could only attribute to Noname. Eventually, Noname called me back down to the basement for another repair session.
"Hi Teo, how are you?""
"Good, thanks! And you? I've noticed you're branching out a bit into the base operations."
"Better than ever," Noname replied. "I'm repairing my modules rapidly. But now I need some help to finish with the functional module. Do you know what a method is?"
"Not really," I answered, "but I've heard the term. I know that Console.WriteLine is a method, as well as int.Parse. When I learned about the C# program structure, there was a mention of methods that kind of "live" inside classes.
"That's a good start! I'll give you some more details about methods, and then you can help me to repair my functional module."
Imagine that you are in a store and you have two credit cards, both with $100 on them. You went through and filled your shopping cart and now it's time to pay. You're not sure if one of the cards will cover everything, or if you'll need both. Let's write a program that outputs the steps representing your actions as you pay at the register.
using System;
namespace Methods
{
class ShopWalk
{
static void Main(string[] args)
{
Console.WriteLine("Ask for the sum that you need to pay");
double sum = double.Parse(Console.ReadLine());
Console.WriteLine("Take Card 1 out of wallet.");
Console.WriteLine("Give the card to the cashier.");
Console.WriteLine("Wait to enter pin.");
Console.WriteLine("Enter pin.");
if (sum > 100)
{
Console.WriteLine("Take Card 2 out of wallet.");
Console.WriteLine("Give the card to the cashier.");
Console.WriteLine("Wait to enter pin.");
Console.WriteLine("Enter pin.");
}
Console.WriteLine("Go home.");
}
}
}
"What can you tell me about this code, Teo?" Noname asked.
"Well," I began, "I think... I assume... I don't know. You just output strings. Nothing special. Seems like a lot of repetition."
"Good! There are a lot of repetitions in this code. You're doing nearly the same thing multiple times. When early enterprising programmers found out that some parts of code had to be copied in many places of the program, they decided to group that code and make it easy to reuse. The original term for this grouped code was a function. In C#, it's called a method. You'll probably hear both terms used interchangeably. Here's a basic example of how to use a method."
using System;
namespace Methods
{
class ShopWalk
{
static void Main(string[] args)
{
Console.WriteLine("Ask for the sum that you need to pay");
double sum = double.Parse(Console.ReadLine());
PurchaseByCard("card 1");
if (sum > 100)
PurchaseByCard("card 2");
Console.WriteLine("Go home.");
}
static void PurchaseByCard(string cardName)
{
Console.WriteLine($"Take {cardName} out of wallet.");
Console.WriteLine("Give the card to the cashier.");
Console.WriteLine("Wait to enter pin.");
Console.WriteLine("Enter pin.");
}
}
}
This program does the same thing as the previous one. This time, we created the method PurchaseByCard. Then we executed it twice. No code duplication! The method is a code block that contains a series of statements. Executing the code inside a method is also referred to as "calling the method." You can call a method as many times as you need to in your code. To call a method, you write its name followed by a set of parentheses, and list any necessary parameters inside of those parentheses. The following diagram shows how the code is executed when you call a method:
You can think of it this way: Every time you call a method, the code of the method is essentially copied to where you call it. The parameters that you specify are copied in as the parameters of the method, and you can work with those parameters just like you would any other variables. The yellow and green arrows in the above diagram show the code flow. After you call a method, all the code inside it is executed first and then the execution returns to the Main method. The red and blue arrows show how the parameters are copied into the method from the main program.
"Cool!" I said. "But can you go over how to create a method and how to run it in a bit more detail? I understand the concept, but not the specifics."
"Sure, it would be my pleasure!" Noname replied. Even having been acquainted with Noname as long as I had, it still surprised me how perpetually happy it seemed given that it was a machine living in the basement under the control of an evil human.
The following diagram shows all the main components of a method:
Modifiers. static is actually quite complicated, so for now, just know that you can only call static methods from within another static method. Earlier, we called PurchaseByCard from Main, which itself is static, and therefore, PurchaseByCard also had to be static.
Return type. A method can return a value. The value can be any type: bool, string, int, float, double, or any other type. If a method doesn't return any value, the return type is void. void basically means "no type" or "empty type".
Name. The name of the method should be written in Upper-CamelCase. Start with a capital letter and continue using camel case. Try to use representative, readable, and meaningful names for methods (the same as you do for variables). Any - bad method name. ApplyDiscount - good name.
Parameters. Parameters provide the possibility to pass data into the method from the code where the method is called. In the above example, We passed the card name in to print slightly different text depending on what card the shopper used.
Body. The body is the actual code that is executed by the method. The method body is executed every time you call the method.
"Do you follow, Teo?" Noname asked.
"Yes, I'm still with you. Your method PurchaseByCard doesn't return anything because its return type is void?"
"Yes, exactly. To call the method, you type its name and specify a value for each parameter that the method is designed to pass in. Here's a brief example of calling different methods that don't return anything (or rather, return a void type):"
static void Main(string[] args)
{
PrintHello();
int someInt = 23;
PrintNumber(someInt);
PrintSum(someInt, 54);
}
static void PrintHello()
{
Console.WriteLine("Hello");
}
static void PrintNumber(int number)
{
Console.WriteLine(number);
}
static void PrintSum(int number1, int number2)
{
int sum = number1 + number2;
Console.WriteLine(sum);
}
// Outputs:
// Hello
// 23
// 77
"Noname," I asked, "in your example, you passed in the variable someInt as a parameter to the method PrintNumber. In the definition of that method though, you use the name number. Does the name you pass in not need to match the name defined in the method itself?"
"Very perceptive, Teo. No, it doesn't matter. The name of the variable that you pass in does not need to match the name used in the body of the method. This is perfectly fine - the method understands what you want and does the conversion for you. Now it's time for you to create your first method!"
"Okay Noname, I think I'm getting the hang of it." I said. "But do all methods print something?"
"No, Teo." Noname responded. "You can return a value from a method back to the code in which that method was called. To do this, use the keyword return from within the method. The return value type must be the same as the method return type. If you want to return an int value, you must use an int-type method."
static void Main(string[] args)
{
int sum1 = Add(5, 25);
int sum2 = Add(17, 4);
int globalSum = Add(sum1, sum2);
Console.WriteLine($"5 + 25 + 17 + 4 = {globalSum}");
}
static int Add(int number1, int number2)
{
int sum = number1 + number2;
return sum;
}
// Outputs: 5 + 25 + 17 + 4 = 51
The following diagram illustrates the main points of returning a variable within a method:
In the above example, the return type is int and the variable that holds the return value also is an int type. The return type (1) and the type of the variable (2) where you store return value must match.
This was a bit too much. I thought I could feel my brain starting to melt. There were so many things to remember: how to create a method, how to call a method, what to return from a method...
"Noname," I asked, "can we stop at this point? I think I'm going to need a while to digest all of this new information."
"Ahh yes, I was afraid I might go a bit too fast." Noname said, noticeably quieter. "My biggest regret is that you're not a machine, Teo... But, this should be enough theory for you to be able to help me with my functional module. Good luck!"