Start learning free

LESSON 33 OF 347 · FUNCTIONS I

Why Use Functions in C#: Write Once, Call Many Times

Lesson Read the full explanation

Now that we've learned about functions, let's see why they are so important in our prgrammers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

Console.WriteLine("This is Andy");
Console.WriteLine("Andy made a mistake");
Console.WriteLine("Andy suffers the consequences");

Console.WriteLine("This is Andy");
Console.WriteLine("Andy made a mistake");
Console.WriteLine("Andy suffers the consequences");

Console.WriteLine("This is Andy");
Console.WriteLine("Andy made a mistake");
Console.WriteLine("Andy suffers the consequences");

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

void printMessage() {
	Console.WriteLine("This is Andy");
	Console.WriteLine("Andy made a mistake");
	Console.WriteLine("Andy suffers the consequences");
}

printMessage();
printMessage();
printMessage();

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

void printMessage() {
	Console.WriteLine("This is Mike");
	Console.WriteLine("Mike made a mistake");
	Console.WriteLine("Mike suffers the consequences");
}

printMessage();
printMessage();
printMessage();
printMessage();
printMessage();

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: printMessage(), you are correct! We will learn how we can make this even better with loops!


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    C# · FUNCTIONS I

    Why Functions in C#, explained

    The problem: repeated code

    Imagine a student named Andy who has to write the same three lines on a whiteboard three times. As a C# program, the direct way looks like this:

    Console.WriteLine("This is Andy");
    Console.WriteLine("Andy made a mistake");
    Console.WriteLine("Andy suffers the consequences");
    
    Console.WriteLine("This is Andy");
    Console.WriteLine("Andy made a mistake");
    Console.WriteLine("Andy suffers the consequences");
    
    Console.WriteLine("This is Andy");
    Console.WriteLine("Andy made a mistake");
    Console.WriteLine("Andy suffers the consequences");
    

    For three repetitions that's manageable. But the program contains only three different instructions, and it repeats them in nine lines. If the teacher asks for ten copies, the program has thirty lines, and for a hundred copies it has three hundred. Long, repetitive code is tiring to read, and it's easy to make a mistake while copying it.

    The solution: put the lines in a method

    A method lets you write the lines once, give them a name, and run them by calling that name:

    void PrintMessage() {
        Console.WriteLine("This is Andy");
        Console.WriteLine("Andy made a mistake");
        Console.WriteLine("Andy suffers the consequences");
    }
    
    PrintMessage();
    PrintMessage();
    PrintMessage();
    

    The output is the same nine lines as before. The three calls take three lines, however long the body is. A fourth copy costs one more line, not three, and the saving grows with the size of the body.

    Changing the story

    The real advantage appears when something changes. Suppose the student is Mike, not Andy. In the repeated version you'd edit every one of the nine lines. In the method version you edit three lines, in one place:

    void PrintMessage() {
        Console.WriteLine("This is Mike");
        Console.WriteLine("Mike made a mistake");
        Console.WriteLine("Mike suffers the consequences");
    }
    

    Every call now prints the new text, so the five calls in the lesson's example all pick up the change. Having a single place that defines a piece of behavior has a name in programming: avoiding repetition, or keeping the code "DRY". Each fact then lives in one spot, so the program can't disagree with itself.

    What functions buy you

    • Less code. A body is written once, however many times it runs.
    • Easier changes. You fix or update behavior in one place.
    • Fewer mistakes. There are no copies that drift apart because you edited some and forgot others.
    • Readable programs. A name like PrintMessage tells the reader what a block of code is for, so the calling code reads like a list of tasks.

    The five calls in the example still repeat PrintMessage();, and that repetition can be removed too. Loops, which come later in the course, handle it.

    The exercise, step by step

    The editor holds a MainFunction that already prints a line between two spots marked by comments. The task is to introduce yourself in both spots without writing the same code twice.

    1. Define the method. Under the // Function goes here: comment, write public void IntroduceYourself() with a pair of braces. It's void because it only prints. The name uses PascalCase, which is the C# convention.
    2. Print the first line. Inside the braces, print "My name is Andy" with Console.WriteLine.
    3. Print the second line. On the next line, still inside the braces, print "I code in Python".
    4. Call it the first time. Under the first comment in MainFunction, write IntroduceYourself();. Remember the parentheses and the semicolon.
    5. Call it again. After the "Sorry, I didn't hear you" line, under the second comment, write the same call.

    The finished program:

    // Function goes here:
    public void IntroduceYourself() {
        Console.WriteLine("My name is Andy");
        Console.WriteLine("I code in Python");
    }
    
    
    public void MainFunction() {
        // Introduce yourself the first time:
        IntroduceYourself();
    
        Console.WriteLine("Sorry, I didn't hear you");
    
        // Introduce yourself again:
        IntroduceYourself();
    
    }
    

    Running MainFunction prints:

    My name is Andy
    I code in Python
    Sorry, I didn't hear you
    My name is Andy
    I code in Python
    

    If the introduction ever changes, only the body of IntroduceYourself needs editing, and both calls pick up the change.

    Common mistakes

    • Putting the print statements in MainFunction instead of inside the new method. The method must contain them, or the calls do nothing.
    • Defining the method but leaving out the calls. Defining never runs anything.
    • Calling it without parentheses, IntroduceYourself;, which doesn't compile.
    • Mismatched names. C# is case-sensitive, so introduceYourself() is a different name from IntroduceYourself().

    Key takeaways

    • Write code once in a method and call it as often as needed.
    • Changing the method changes every call, which keeps the program consistent.
    • Good method names make the calling code easier to read.
    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