Consider this C# code snippet that uses value and reference types. What will be printed?
int a = 5; int b = a; b = 10; Console.WriteLine(a);
Think about how value types are copied in memory.
In C#, integers are value types. When you assign b = a, it copies the value. Changing b does not affect a. So a remains 5.
Look at this code that uses a class instance. What will be printed?
class Box { public int Size; } Box box1 = new Box() { Size = 5 }; Box box2 = box1; box2.Size = 10; Console.WriteLine(box1.Size);
Remember how reference types share the same memory location.
Classes are reference types. Both box1 and box2 point to the same object. Changing box2.Size changes box1.Size too.
Examine this code snippet. What error will it cause when run?
int[] numbers = new int[3]; numbers[3] = 10; Console.WriteLine(numbers[3]);
Check the array size and the index used.
The array has size 3, so valid indices are 0, 1, 2. Accessing index 3 is out of bounds and throws IndexOutOfRangeException.
Which statement best explains why knowing the difference between stack and heap memory matters in C#?
Think about where value and reference types live and how that affects speed and memory cleanup.
Value types are stored on the stack which is fast and short-lived. Reference types are stored on the heap which is slower but allows dynamic memory and is managed by the garbage collector.
Analyze this code and determine how many objects are created in memory.
class Person { public string Name; } Person p1 = new Person() { Name = "Alice" }; Person p2 = new Person() { Name = "Alice" }; string s = "Alice";
Consider how string literals are interned and how many class instances are created.
Two Person objects are created with new. The string "Alice" is interned, so only one string object exists despite multiple references. Total objects created in memory: 3.