CodeBlanks Logo Icon CodeBlanks

Defining methods

C# course · Beginner · Lesson 71/116

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

  1. 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").

  2. Method body

    static void Greet()
    {
        ____
    }
    Show answer
    static void Greet()
    {
        Console.WriteLine("Hello");
    }
  3. Match each keyword to its meaning

    static
    Class-level
    void
    No return value
    Greet()
    Method call
    Main()
    Entry point

All lessons in Beginner