C# Methods
A method is a block of code that runs when it is called. A method groups one job so the job can run more than once.
Define and call
ShowMessage prints one line when Main calls it. The word static lets Main call the method directly.
using System;
class Program
{
static void ShowMessage()
{
Console.WriteLine("Hello from a method");
}
static void Main(string[] args)
{
ShowMessage();
}
}Call a method twice
Main calls PrintLine two times. Each call prints the line again.
using System;
class Program
{
static void PrintLine()
{
Console.WriteLine("Ready");
}
static void Main(string[] args)
{
PrintLine();
PrintLine();
}
}Two methods in order
Main calls Start and then Finish. The lines print in call order.
using System;
class Program
{
static void Start()
{
Console.WriteLine("Start");
}
static void Finish()
{
Console.WriteLine("Finish");
}
static void Main(string[] args)
{
Start();
Finish();
}
}Example
using System;
class Program
{
static void PrintHeader()
{
Console.WriteLine("Receipt");
}
static void PrintDetails()
{
Console.WriteLine("Apples: 2");
Console.WriteLine("Total: 5");
}
static void Main(string[] args)
{
PrintHeader();
PrintDetails();
}
}Key points
- A method call writes the method name and parentheses.
- The void keyword means the method returns no value.
- The static keyword lets Main call a method directly.
- Code inside a method runs only when the method is called.
- Each call runs the method body again from the top.
- Methods sit inside the class beside Main.
In this example, Main calls PrintHeader first. PrintHeader prints the Receipt line. Main then calls PrintDetails. PrintDetails prints the Apples line and then the Total line.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What happens each time a method is called?