CodeBlanks Logo Icon CodeBlanks

void methods

C# course · Beginner · Lesson 73/116

Learn void methods that do not return a value.

void methods

The void return type means the method returns no value. Such methods perform a side effect: they print to the screen, change state, or write to a file. They give nothing back.

Example: static void PrintLine(string text) { Console.WriteLine(text); }. This method takes a string and prints it to the screen; there is nothing to return to the caller.

void and return

The body of a void method has no return statement. Still, you can exit early with return; (no value). It is used to end the method immediately when a condition is met.

You cannot use a method that returns nothing in an assignment: int x = PrintLine("hello"); gives a compile error. Because void is not a value.

Exercise Print method

Define a static void PrintLine(string text) method; in the body call Console.WriteLine(text). In Main, call it with PrintLine("Hello").

Show example solution
Add Console.WriteLine(text); to the PrintLine body, write PrintLine("Hello"); in Main.
Example solution:
using System;

class Program
{
    static void PrintLine(string text)
    {
        // Print text
        Console.WriteLine(text);
    }

    static void Main()
    {
        // Call PrintLine with "Hello"
        PrintLine("Hello");
    }
}

Test yourself

  1. void method body

    static void PrintLine(string text)
    {
        ____
    }
    Show answer
    static void PrintLine(string text)
    {
        Console.WriteLine(text);
    }
  2. Match each expression to its meaning

    void
    No value
    return 5;
    Returns 5
    Console.WriteLine
    Side effect
    static
    Class-level
  3. What does the SayHi() call print?

    static void SayHi()
    {
        Console.WriteLine("Hi");
    }
    SayHi();
    • Hello
    • Hi
    • Hey
    • void
    Show answer

    Hi — Correct. The SayHi body runs Console.WriteLine("Hi").

All lessons in Beginner