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

Value type copying behavior in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Value Type Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
A0
B20
C5
DCompilation error
Attempts:
2 left
💡 Hint
Remember that structs are value types and copying creates a new independent copy.
Predict Output
intermediate
2:00remaining
Effect of modifying a copied value type
Consider this code:
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);
A30
B10
C0
DCompilation error
Attempts:
2 left
💡 Hint
int is a value type, so assignment copies the value.
Predict Output
advanced
2: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);
ACompilation error
B100
C0
D50
Attempts:
2 left
💡 Hint
Value types are passed by value by default.
Predict Output
advanced
2: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);
A99
BCompilation error
C0
D10
Attempts:
2 left
💡 Hint
The ref keyword passes the value type by reference, allowing modification.
🧠 Conceptual
expert
2:00remaining
Understanding boxing and value type copying
Which statement best describes what happens when a value type is boxed in C#?
AA reference type object is created on the heap containing a copy of the value type data.
BThe value type is passed by reference to avoid copying.
CThe original value type is converted into a reference type without copying data.
DThe value type is converted into a pointer to the original data.
Attempts:
2 left
💡 Hint
Boxing involves creating an object on the heap.