C#.NET string interning and object references: consider the code String s1, s2; s1 = 'Hi'; s2 = 'Hi'; Which statements about object creation and references are true?

Difficulty: Easy

Correct Answer: 2, 3, 5

Explanation:


Introduction / Context:
This item tests understanding of string interning and reference behavior in C#.NET. String literals are interned, which can cause multiple variables initialized with the same literal to point to the same object instance.



Given Data / Assumptions:

  • Two string variables s1 and s2.
  • Both assigned the same literal 'Hi'.
  • Statements to evaluate include whether objects are created with or without new, and whether references point to the same instance.


Concept / Approach:
In .NET, string literals are interned. Assigning the same literal to two variables does not create two different heap objects; both references point to the interned single instance. Creating strings without new is perfectly legal through literals.



Step-by-Step Solution:

1) 'String objects cannot be created without using new.' → False: literals create interned strings.2) 'Only one object will get created.' → True due to interning.3) 's1 and s2 both will refer to the same object.' → True: both refer to interned 'Hi'.4) 'Two objects will get created…' → False.5) 's1 and s2 are references to the same object.' → True (same as 3).


Verification / Alternative check:
Use Object.ReferenceEquals(s1, s2) → returns true. Using new string('H',1) etc. would bypass interning unless explicitly interned.



Why Other Options Are Wrong:
Any option including 1 or 4 is incorrect because they contradict interning and literal semantics.



Common Pitfalls:
Confusing content equality with reference equality; assuming every assignment creates a new object on the heap.



Final Answer:
2, 3, 5

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion