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

Reference assignment and shared state in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reference 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 code?
Consider the following C# code snippet. What will be printed to the console?
C Sharp (C#)
class Box {
    public int Value;
}

Box a = new Box();
a.Value = 5;
Box b = a;
b.Value = 10;
Console.WriteLine(a.Value);
A10
B5
C0
DCompilation error
Attempts:
2 left
💡 Hint
Remember that classes are reference types in C#.
Predict Output
intermediate
2:00remaining
What is the output of this code with structs?
What will this C# code print to the console?
C Sharp (C#)
struct Point {
    public int X;
    public int Y;
}

Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1;
p2.X = 5;
Console.WriteLine(p1.X);
A5
B1
C0
DCompilation error
Attempts:
2 left
💡 Hint
Structs are value types in C#.
🔧 Debug
advanced
2:30remaining
Why does this code print 0 instead of 10?
Examine the code below. It is intended to print 10, but it prints 0 instead. What is the reason?
C Sharp (C#)
class Counter {
    public int Count;
}

void Increment(Counter c) {
    c = new Counter();
    c.Count = 10;
}

Counter myCounter = new Counter();
Increment(myCounter);
Console.WriteLine(myCounter.Count);
AThe Counter class is a struct and is copied by value.
BThe Count field is private and cannot be accessed.
CThe method assigns a new object to the parameter, which does not affect the original reference.
DThe method Increment is never called.
Attempts:
2 left
💡 Hint
Think about how reference parameters work in C#.
Predict Output
advanced
2:30remaining
What is the output of this code using ref keyword?
What will this C# code print to the console?
C Sharp (C#)
class Number {
    public int Value;
}

void Change(ref Number n) {
    n = new Number();
    n.Value = 20;
}

Number num = new Number();
num.Value = 5;
Change(ref num);
Console.WriteLine(num.Value);
A20
B5
C0
DCompilation error
Attempts:
2 left
💡 Hint
The ref keyword allows the method to modify the caller's reference.
🧠 Conceptual
expert
3:00remaining
How many distinct objects exist after this code runs?
Consider this C# code snippet. How many distinct Person objects exist in memory after execution?
C Sharp (C#)
class Person {
    public string Name;
}

Person p1 = new Person { Name = "Alice" };
Person p2 = p1;
p2.Name = "Bob";
p2 = new Person { Name = "Charlie" };
A1
B3
C0
D2
Attempts:
2 left
💡 Hint
Count how many times new objects are created.