Start learning free

LESSON 34 OF 347 · FUNCTIONS I

Create a Method in C#: Refactoring Repeated Code

Practice Read the full explanation

We've wrritten this code:

void mainFunction() {
	Console.WriteLine("Hello AlgoCademy!");
	Console.WriteLine("Coding is amazing!");
	Console.WriteLine("Functions are so useful!");

	Console.WriteLine("Hello AlgoCademy!");
	Console.WriteLine("Coding is amazing!");
	Console.WriteLine("Functions are so useful!");

	Console.WriteLine("Hello AlgoCademy!");
	Console.WriteLine("Coding is amazing!");
	Console.WriteLine("Functions are so useful!");
}

Write the same code in a better way by creating and calling a function printMessages()

STEP 1 OF 2
    Ctrl + Enter to check

    C# · FUNCTIONS I

    Exercise Create Function in C#, explained

    Problem overview

    The starting program prints three messages, and it prints the same three messages three times in a row: Hello AlgoCademy!, Coding is amazing! and Functions are so useful!. That is nine Console.WriteLine lines for something that is really one idea repeated.

    The task is to write the same program in a better way, by creating a method called PrintMessages and calling it. The output must stay exactly the same: the three lines, three times.

    Approach

    When the same group of statements appears several times, move the group into a method. Then the group is written once, and each repetition becomes a single call. This makes the program shorter, and it means the messages can be changed in one place.

    The lesson asks for the method name PrintMessages. The task statement writes it in lower case, but the code and the steps use PascalCase, which is the C# convention, so that is the name to use.

    Step by step

    1. Define the method above MainFunction. Write public void PrintMessages() with braces. It takes no inputs, so the parentheses are empty. It's void because it only prints and gives nothing back.
    2. Move one copy of the messages into the body. Put the three Console.WriteLine lines between the braces. Only one copy goes in, because the method is what repeats them.
    3. Call it three times from MainFunction. Write PrintMessages(); on three lines. Each call runs the whole body once, so the messages are printed three times.

    The order of the definition and MainFunction in the file doesn't matter to the compiler, but the lesson puts the method first so the program reads in the order you'd explain it.

    The solution in C#

    // Define and implement the function PrintMessages here:
    public void PrintMessages() {
        Console.WriteLine("Hello AlgoCademy!");
        Console.WriteLine("Coding is amazing!");
        Console.WriteLine("Functions are so useful!");
    }
    
    
    public void MainFunction() {
        // Call PrintMessages 3 times here:
        PrintMessages();
        PrintMessages();
        PrintMessages();
    }
    

    Running MainFunction prints:

    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    

    Reading the header

    Each word in public void PrintMessages() has a job. public says other code may call the method, which is what MainFunction needs to do. void is the return type, meaning nothing is handed back. PrintMessages is the name, and the empty parentheses are the parameter list: this method needs no inputs to do its work. A later lesson fills those parentheses in, so the same method can print different messages.

    Following the run

    When MainFunction reaches the first PrintMessages();, control jumps into the method and runs its three prints in order. Then it comes back to MainFunction and moves to the second call, and so on. Three calls mean three trips into the method, and nine lines in the output.

    C# details to watch

    • Parentheses make the call. PrintMessages(); runs the method. The bare name PrintMessages; isn't a valid statement, so it won't compile.
    • The text in quotes must match exactly. A string literal is compared character for character, including capital letters, spaces and the exclamation mark. A message that differs in one character gives different output.
    • Each statement ends with a semicolon. The method's closing brace does not.
    • void means no return value. There is no return statement, and nothing is returned to the caller.
    • Names are case-sensitive. The definition and the three calls must all spell it PrintMessages.

    Edge cases and common mistakes

    • Leaving the old lines in MainFunction. If the nine original lines stay, the messages print again on top of the calls. Remove them; the calls replace them.
    • Copying the three messages into the method three times. That would print each message three times every call. One copy only.
    • Calling the method fewer or more than three times. The output has to match the original program, which printed the group three times.
    • Defining without calling. A program with only the definition prints nothing.

    Why this is better

    Compare how the two versions behave when something changes. To reword a message in the original, you'd edit it in three places. In the new version, you edit it once, inside PrintMessages, and all three calls pick it up. To print the group a fourth time, you add one line instead of three. The method also gives the group a name that says what it does, which makes MainFunction read like a short list of actions.

    You can try changing one message in the method and running it again to see all three groups change together.

    Testing

    A good way to check your work is to count. One call should print exactly three lines, two calls six lines, and three calls nine lines. If the count is off, either the body holds the wrong number of prints or MainFunction has the wrong number of calls. Also compare the text of each message with the task, character by character, since a small typo changes the output.

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free