Challenge - 5 Problems
Value Type Passing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of passing value type to method
What is the output of the following C# code?
C Sharp (C#)
using System; class Program { static void Increment(int x) { x = x + 1; } static void Main() { int a = 5; Increment(a); Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
Remember that value types are passed by value by default.
✗ Incorrect
The method Increment receives a copy of the value of 'a'. Changing 'x' inside the method does not affect 'a' in Main. So the output remains 5.
❓ Predict Output
intermediate2:00remaining
Effect of ref keyword on value type parameter
What will be printed by this C# program?
C Sharp (C#)
using System; class Program { static void Increment(ref int x) { x = x + 1; } static void Main() { int a = 5; Increment(ref a); Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
The ref keyword passes the variable by reference.
✗ Incorrect
Using ref passes the variable itself, so changes inside Increment affect 'a'. Thus, 'a' becomes 6.
🔧 Debug
advanced2:00remaining
Identify the error when passing value type without ref
What error will this code produce?
C Sharp (C#)
using System; class Program { static void Increment(ref int x) { x = x + 1; } static void Main() { int a = 5; Increment(a); Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
Check how ref parameters must be called.
✗ Incorrect
The method requires 'ref' keyword when calling. Omitting it causes a compile-time error.
❓ Predict Output
advanced2:00remaining
Passing struct value type to method and modifying fields
What is the output of this C# program?
C Sharp (C#)
using System; struct Point { public int X; public int Y; } class Program { static void Move(Point p) { p.X += 10; p.Y += 10; } static void Main() { Point pt = new Point { X = 1, Y = 1 }; Move(pt); Console.WriteLine($"{pt.X}, {pt.Y}"); } }
Attempts:
2 left
💡 Hint
Structs are value types and passed by value by default.
✗ Incorrect
The method Move receives a copy of the struct. Modifying the copy does not change the original 'pt'.
❓ Predict Output
expert2:00remaining
Passing value type with out parameter
What will be the output of this C# program?
C Sharp (C#)
using System; class Program { static void Initialize(out int x) { x = 10; } static void Main() { int a; Initialize(out a); Console.WriteLine(a); } }
Attempts:
2 left
💡 Hint
Out parameters must be assigned inside the method before use.
✗ Incorrect
The out parameter 'x' is assigned 10 inside Initialize, so 'a' gets value 10.