Challenge - 5 Problems
Ref and Out Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method using ref parameter
What is the output of the following C# code?
C Sharp (C#)
using System; class Program { static void Increment(ref int x) { x += 5; } static void Main() { int a = 10; Increment(ref a); Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
Remember that ref passes the variable by reference, so changes inside the method affect the original variable.
✗ Incorrect
The method Increment adds 5 to the variable passed by ref, so the original variable 'a' changes from 10 to 15.
❓ Predict Output
intermediate2:00remaining
Output of method using out parameter
What will be printed when this C# code runs?
C Sharp (C#)
using System; class Program { static void GetValues(out int x, out int y) { x = 3; y = 7; } static void Main() { int a, b; GetValues(out a, out b); Console.WriteLine(a + b); } }
Attempts:
2 left
💡 Hint
Out parameters must be assigned inside the method before use.
✗ Incorrect
The method assigns 3 to x and 7 to y, so a + b equals 10.
❓ Predict Output
advanced2:00remaining
Behavior of ref vs out with uninitialized variables
What happens when you try to compile and run this C# code?
C Sharp (C#)
using System; class Program { static void Modify(ref int x) { x = 10; } static void ModifyOut(out int y) { y = 20; } static void Main() { int a; //Modify(ref a); // Line 1 ModifyOut(out a); // Line 2 Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
ref requires the variable to be initialized before passing; out does not.
✗ Incorrect
Line 1 is commented out because passing uninitialized variable by ref causes compile error. Line 2 is valid because out parameters do not require initialization before passing. The method assigns 20 to 'a', so output is 20.
🧠 Conceptual
advanced2:00remaining
Difference between ref and out parameters
Which statement correctly describes the difference between ref and out parameters in C#?
Attempts:
2 left
💡 Hint
Think about initialization requirements and assignment inside the method.
✗ Incorrect
ref parameters require the variable to be initialized before passing, while out parameters do not require initialization but must be assigned inside the method before use.
🔧 Debug
expert2:00remaining
Identify the error in this code using ref and out
What error will this C# code produce when compiled?
C Sharp (C#)
using System; class Program { static void Process(ref int x, out int y) { x += 5; // y is not assigned } static void Main() { int a = 1, b; Process(ref a, out b); Console.WriteLine(a + b); } }
Attempts:
2 left
💡 Hint
Out parameters must be assigned a value inside the method before returning.
✗ Incorrect
The method Process does not assign a value to the out parameter 'y', causing a compilation error.