Consider the following C# code snippet. What will be printed to the console?
using System; class Program { static void Main() { int x = 10; int y = x; y = 20; Console.WriteLine(x); } }
Think about where value types like int are stored and how assignment works.
Variables x and y are value types stored on the stack. Assigning y = x copies the value. Changing y does not affect x. So x remains 10.
Look at this C# code. What will it print?
using System; class Program { class Box { public int Value; } static void Main() { Box a = new Box(); a.Value = 5; Box b = a; b.Value = 10; Console.WriteLine(a.Value); } }
Remember that classes are reference types stored on the heap.
Both a and b point to the same object on the heap. Changing b.Value changes the object, so a.Value is also 10.
Choose the statement that correctly explains the difference between stack and heap memory in C#.
Think about where value types and reference types are stored during execution.
In C#, the stack holds value types and method call info (like parameters and local variables). The heap stores objects created by reference types.
Examine the code below. Why does it throw a NullReferenceException?
using System; class Program { class Container { public string Text; } static void Main() { Container c = null; c.Text = "Hello"; Console.WriteLine(c.Text); } }
Think about what happens when you try to access a member of a null reference.
c is a reference type variable set to null. Trying to access c.Text causes a NullReferenceException because there is no actual object.
Consider this C# code snippet. How many objects are created on the heap after Main finishes?
using System; class Program { class Node { public int Value; public Node Next; } static void Main() { Node first = new Node(); first.Value = 1; Node second = new Node(); second.Value = 2; first.Next = second; Node third = second; } }
Count how many times new is used to create objects.
Two new Node() calls create two objects on the heap. The variable third just references the existing second object.