CodeGym /Courses /C# SELF /Return Value and the return Statement

Return Value and the return Statement

C# SELF
Level 8, Lesson 3
Available

1. Intro

Let's imagine: you're ordering a pizza by phone (or, you know, through an app, it's the 21st century after all). You tell the operator your order details, and the operator gives you the result: a pizza! If the operator stays silent—you stay hungry, and there's no happiness.

Same thing with functions: sometimes their job is just to do something, but often you want the function to give you something useful back, and the result can be different every time depending on the input! For example:

  • A function calculates the sum of two numbers and gives you the result.
  • A function gets a person's age and returns a category ("child", "adult", "senior").
  • A function creates a nice greeting string for a user by name.

Return value — a way for a function to “hand over” the result of its work to the outside.

2. Method Signature with a Return Value

In the last lecture, we saw a template like this:

void PrintHello()
{
    Console.WriteLine("Hello!");
}
Method with no return value ( void)

The void type means the function doesn't return anything (void means "empty", no value).

Now let's see what a function looks like when it does return something:

int Add(int a, int b)
{
    // function body
}
Method with a return value ( int)

Here, int before the function name is the data type of the return value. So, if the function returns a string—write string, if it's a floating point—double, and so on.

The syntax for declaring a function looks like this:

<return type> MethodName(<parameters>)
{
    // function body
}
General template for a method with a return value

Examples of different signatures:

Signature What it returns
int Sum(int a, int b)
An integer
string GetGreeting(string name)
A string
double Multiply(double x, double y)
A floating point number
bool IsAdult(int age)
A boolean value

3. The return Statement: How to Return a Result from a Function

To make it all work, it's not enough to just specify the right type—you need to teach the function to send the result back “upstairs.” That's what the return statement is for. With it, we say: here, I'm returning this value, and at that point the function stops running (it kind of "jumps out" right then).

type MethodName(...)
{
    // some calculations
    return value;
}
How to use return

Example:

int Add(int a, int b)
{
    int sum = a + b;
    return sum; // sending the sum as the function's result
}

Important rule: the type of the value you return with return must exactly match (or be compatible with) the type you wrote in the method signature.

4. Examples: Writing Methods That Return Something

Let's jump right into examples! Here are a few common cases.

Example 1: Adding two numbers

int Add(int a, int b)
{
    return a + b;
}

// Usage:
int result = Add(10, 20);
Console.WriteLine("Sum: " + result); // Output: Sum: 30

Example 2: Personalized greeting

string CreateGreeting(string name)
{
    return "Hello, " + name + "!";
}

// Usage:
string greeting = CreateGreeting("Anna");
Console.WriteLine(greeting); // Output: Hello, Anna!

Example 3: Checking adulthood

bool IsAdult(int age)
{
    return age >= 18;
}

if (IsAdult(21))
{
    Console.WriteLine("Entry allowed.");
}
else
{
    Console.WriteLine("Sorry, adults only.");
}
// Output: Entry allowed.

Example 4: Return value and using it in expressions

Console.WriteLine("Twice as much: " + MultiplyByTwo(7));

int MultiplyByTwo(int n)
{
    return n * 2;
}

5. Return Type: Variety and Features

In C#, a function can return any "type" (not just numbers, strings, and the usual stuff). Here are a few cases:

  • Integers: int, long, short — easy stuff.
  • Floating point: double, float, decimal.
  • Strings: string.
  • Booleans: bool.
  • Arrays: int[], string[] and so on.
  • Reference types: objects of classes you created.
  • void: special case, when nothing is returned.

Why is the return type so important?

The compiler keeps a close eye to make sure you return what you promised. If you said you'd return an int, but try to return a string or nothing at all—you'll get an error. It's like a strict boss.

Example of an error:

int GetNumber()
{
    return "42"; // Error! Expected int, not string.
}

6. The return Statement Without a Value: For void Methods

To be fair, in methods with a declared return type (like int, string), the return statement always has to be followed by the value you want to return.

But! If the function is declared with the void type, you can still, if you want, use return with no value—just to immediately stop the function.

void PrintNumbers(int n)
{
    if (n <= 0)
    {
        Console.WriteLine("Number must not be negative!");
        return; // Just exit the function, don't return anything
    }
    for (int i = 1; i <= n; i++)
    {
        Console.WriteLine(i);
    }
}
return without a value in a void method

This can be handy if you want to stop the function early for some reason, but you don't need to return anything.

7. Common Mistakes When Using return

Oh man, beginner devs often bang their heads over mistakes with return!

Problem #1: no return in a function that's supposed to return something

int GetValue(bool flag)
{
    if (flag)
        return 1;
    // Oops! What if flag == false?
}
// Error: not all code paths return a value!

Solution: always make sure you have a return for every possible way the function can run! For example:

int GetValue(bool flag)
{
    if (flag)
        return 1;
    else
        return 0;
}

Problem #2: return type mismatch

double GetMagicNumber()
{
    return 42; // Actually, this is fine (int can be implicitly converted to double)
    // But if the function returned int and you returned a string—you'd get an error!
}

Rule: watch out for type compatibility. If you're not sure—just cast it to the right type:

return (double)42;

Problem #3: return at the wrong time

Remember, as soon as return runs, the method stops right there. Anything after it won't run!

int GetNumber()
{
    return 5;
    Console.WriteLine("This line will never run"); // the compiler will even complain!
}

Problem #4: return with a value in a void method (not allowed!)

void PrintSomething()
{
    return 1; // You can't return a value from a void method!
}
2
Task
C# SELF, level 8, lesson 3
Locked
A method that returns a greeting string
A method that returns a greeting string
2
Task
C# SELF, level 8, lesson 3
Locked
Method to Check if a Number is Even
Method to Check if a Number is Even
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION