Challenge - 5 Problems
Value Type Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of struct value copy
What is the output of this C# code?
struct Point { public int X; public int Y; }
Point p1 = new Point { X = 5, Y = 10 };
Point p2 = p1;
p2.X = 20;
Console.WriteLine(p1.X);C Sharp (C#)
struct Point { public int X; public int Y; }
Point p1 = new Point { X = 5, Y = 10 };
Point p2 = p1;
p2.X = 20;
Console.WriteLine(p1.X);Attempts:
2 left
💡 Hint
Remember that structs are value types and copying creates a new independent copy.
✗ Incorrect
In C#, structs are value types. When you assign p1 to p2, a copy of the data is made. Changing p2.X does not affect p1.X, so p1.X remains 5.
❓ Predict Output
intermediate2:00remaining
Effect of modifying a copied value type
Consider this code:
What will be printed?
int a = 10;
int b = a;
b = 30;
Console.WriteLine(a);
What will be printed?
C Sharp (C#)
int a = 10; int b = a; b = 30; Console.WriteLine(a);
Attempts:
2 left
💡 Hint
int is a value type, so assignment copies the value.
✗ Incorrect
Assigning b = a copies the value 10. Changing b to 30 does not affect a, so a remains 10.
❓ Predict Output
advanced2:00remaining
Value type in method parameter behavior
What is the output of this code?
struct Number { public int Value; }
void Change(Number n) { n.Value = 100; }
Number num = new Number { Value = 50 };
Change(num);
Console.WriteLine(num.Value);C Sharp (C#)
struct Number { public int Value; }
void Change(Number n) { n.Value = 100; }
Number num = new Number { Value = 50 };
Change(num);
Console.WriteLine(num.Value);Attempts:
2 left
💡 Hint
Value types are passed by value by default.
✗ Incorrect
The method Change receives a copy of num. Modifying n.Value changes only the copy, so num.Value remains 50.
❓ Predict Output
advanced2:00remaining
Effect of ref keyword on value type parameter
What will this code print?
struct Data { public int X; }
void Modify(ref Data d) { d.X = 99; }
Data data = new Data { X = 10 };
Modify(ref data);
Console.WriteLine(data.X);C Sharp (C#)
struct Data { public int X; }
void Modify(ref Data d) { d.X = 99; }
Data data = new Data { X = 10 };
Modify(ref data);
Console.WriteLine(data.X);Attempts:
2 left
💡 Hint
The ref keyword passes the value type by reference, allowing modification.
✗ Incorrect
Using ref passes the struct by reference, so changes inside Modify affect the original data. data.X becomes 99.
🧠 Conceptual
expert2:00remaining
Understanding boxing and value type copying
Which statement best describes what happens when a value type is boxed in C#?
Attempts:
2 left
💡 Hint
Boxing involves creating an object on the heap.
✗ Incorrect
Boxing copies the value type data into a new object on the heap, which is a reference type. This allows value types to be treated as objects.