Learn C# · lesson 22 of 61 · about 7 minutes
Defining Methods
End the battle between two dividers: package a line of code into your own method and call it as often as you like.
What you'll learn
- Write a method with void
- Call a method
- Know where methods go in a program
A divider for the end
The battle's output is getting long, so its end should stand out, with a divider line above and below it. The same Console.WriteLine twice would work, but if the divider ever changes it has to be changed twice. A method gives that line a name, PrintDivider, and every call prints it.
Naming a piece of work
A method is a named block of code:
static void Greet() { Console.WriteLine("Hi!"); }
voidmeans it doesn't give back a value- Call it with brackets:
Greet(); - In a program with top-level statements, write methods below the main code; you can still call them from above
- C# method names use PascalCase:
PrintBanner, notprintBanner
Define it, then call it
Wave();
static void Wave()
{
Console.WriteLine("Hi!");
}Output
Hi!A banner method
PrintBanner();
Console.WriteLine("Welcome to Codiqo");
PrintBanner();
static void PrintBanner()
{
Console.WriteLine(new string('=', 17));
}Output
=================
Welcome to Codiqo
=================Why bother?
- Reuse: write it once, call it many times
- Names:
PrintMenu()explains itself - Fix once: a bug fixed in the method is fixed everywhere it's used
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.