0
0
C Sharp (C#)programming~20 mins

Return values and void methods in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Return Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this C# code with return values?
Look at this code. What will it print when run?
C Sharp (C#)
using System;
class Program {
    static int MultiplyByTwo(int x) {
        return x * 2;
    }
    static void Main() {
        int result = MultiplyByTwo(5);
        Console.WriteLine(result);
    }
}
A10
B5
C0
DNothing, it causes a compile error
Attempts:
2 left
💡 Hint
The method MultiplyByTwo returns the input number multiplied by 2.
Predict Output
intermediate
2:00remaining
What will this void method print?
Check this code. What does it print when run?
C Sharp (C#)
using System;
class Program {
    static void PrintMessage() {
        Console.WriteLine("Hello World");
    }
    static void Main() {
        PrintMessage();
    }
}
AHello World
BCompile error because void methods cannot be called
CHelloWorld (without space)
DNothing, because void methods don't print
Attempts:
2 left
💡 Hint
Void methods can print to the screen using Console.WriteLine.
Predict Output
advanced
2:00remaining
What is the output of this method returning a string?
What does this program print when run?
C Sharp (C#)
using System;
class Program {
    static string GetGreeting(string name) {
        return $"Hi, {name}!";
    }
    static void Main() {
        string greet = GetGreeting("Anna");
        Console.WriteLine(greet);
    }
}
AHi Anna!
BHi, Anna!
CHi, {name}!
DCompile error due to string interpolation
Attempts:
2 left
💡 Hint
The method uses string interpolation to insert the name.
Predict Output
advanced
2:00remaining
What happens if you try to return a value from a void method?
Look at this code. What error will it cause?
C Sharp (C#)
using System;
class Program {
    static void DoSomething() {
        return 5;
    }
    static void Main() {
        DoSomething();
    }
}
ANo error, returns 5 silently
BPrints 5
CRuntime error
DCompile error: Cannot return a value from a method with void return type
Attempts:
2 left
💡 Hint
Void methods cannot return any value.
🧠 Conceptual
expert
2:00remaining
How many items are in the list after this method runs?
Consider this code. How many items does the list contain after Main runs?
C Sharp (C#)
using System;
using System.Collections.Generic;
class Program {
    static List<int> AddNumbers() {
        var list = new List<int>();
        for (int i = 0; i < 3; i++) {
            list.Add(i);
        }
        return list;
    }
    static void Main() {
        var numbers = AddNumbers();
        numbers.Add(3);
        Console.WriteLine(numbers.Count);
    }
}
A0
B3
C4
DCompile error
Attempts:
2 left
💡 Hint
The method adds 3 items, then Main adds one more.