Defining methods
Learn how to define and call a method.
Defining methods
A method is a named block of code that runs when called. In C#, a method is declared with the static keyword, a return type, a name, and parameters inside parentheses. The body goes inside curly braces.
Example: static void Greet() { Console.WriteLine("Hello"); }. Here void means no return value, Greet is the method name. To call it, write its name followed by parentheses: Greet();.
Calling and Main
A method is called from Main by writing its name and parentheses. The parentheses are required; if you write only the name, it is a reference, not a call. Main is the entry point of the program; when the application starts, it runs first.
A method can be called as many times as needed inside its class. Referring to a method instead of repeating the same code shortens the code and makes it more readable.
Exercise Greet method
Define a static void Greet() method; in its body write Console.WriteLine("Hello"). Call Greet() from Main.
Show example solution
Add Console.WriteLine("Hello"); to the Greet body and write Greet(); in Main.
Example solution:
using System;
class Program
{
static void Greet()
{
// Print Hello
Console.WriteLine("Hello");
}
static void Main()
{
// Call Greet
Greet();
}
}
Test yourself
-
What does the Greet() call print?
static void Greet() { Console.WriteLine("Hello"); } Greet();- Hello
- Hi
- Greet
- Empty
Show answer
Hello — Correct. The Greet body runs Console.WriteLine("Hello").
-
Method body
static void Greet() { ____ }Show answer
static void Greet() { Console.WriteLine("Hello"); } -
Match each keyword to its meaning
- static
- Class-level
- void
- No return value
- Greet()
- Method call
- Main()
- Entry point