wasAsked.

object is a reference type. Predict the output of a code snippet based on this concept.

PwC · Role not specified · technical

Published

Asked in 2026 · Software Engineering

Community answers

Posted by wasAsked editorial collection

These "predict the output" questions test whether you understand reference semantics: variables of reference types hold references to objects, not the objects themselves. Here are the classic snippets and their outputs. 1. Two variables, one object class Box { public int Value; } var a = new Box { Value = 1 }; var b = a; // copies the reference b.Value = 2; Console.WriteLine(a.Value); // 2 — a and b point to the same object 2. Reassigning a reference does not affect the other variable var a = new Box { Value = 1 }; var b = a; b = new Box { Value = 5 }; // b now points to a different object Console.WriteLine(a.Value); // 1 3. Passing to a method (reference passed by value) void Change(Box box) { box.Value = 10; } // modifies the shared object void Replace(Box box) { box = new Box { Value = 99 }; } // only changes the local copy of the reference var x = new Box { Value = 1 }; Change(x); Console.WriteLine(x.Value); // 10 Replace(x); Console.WriteLine(x.Value); // 10 — still the same object 4. With ref, the caller's variable can be replaced void ReplaceRef(ref Box box) { box = new Box { Value = 99 }; } ReplaceRef(ref x); Console.WriteLine(x.Value); // 99 5. object and boxing — value types copied into a box int n = 5; object o = n; // boxing copies the value n = 10; Console.WriteLine(o); // 5 object o1 = 5, o2 = 5; Console.WriteLine(o1 == o2); // False — == on object compares references (two different boxes) Console.WriteLine(o1.Equals(o2)); // True — Equals compares the boxed int values 6. Strings: reference type, but immutable with value equality string s1 = "hi"; string s2 = s1; s2 += "!"; // creates a new string Console.WriteLine(s1); // hi object a1 = "hello"; object a2 = new string("hello".ToCharArray()); Console.WriteLine(a1 == a2); // False — reference comparison through object (different instances) Console.WriteLine(a1.Equals(a2)); // True — string.Equals compares contents 7. Structs vs classes struct Point { public int X; } var p1 = new Point { X = 1 }; var p2 = p1; p2.X = 2; Console.WriteLine(p1.X); // 1 — structs are copied How to explain your reasoning: identify whether each variable holds a reference or a value, whether an assignment copies the reference or creates a new object, and which equality is used (== on object is reference equality unless the static type defines its own operator; Equals is virtual and type-specific).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics