C#.NET — What actually happens in: sample c; c = new sample(); Choose the correct interpretation.

Difficulty: Easy

Correct Answer: 2, 4

Explanation:


Introduction / Context:
This examines reference vs object allocation in C#. For classes (reference types), variables hold references; the new operator allocates an instance (object) on the managed heap.



Given Data / Assumptions:

  • sample is a class type.
  • c is a local variable (stored as a reference).


Concept / Approach:
In c = new sample(); the expression new sample() creates a new object; the object itself does not have an identifier (name) — only the reference variable c has a name. Hence it is sometimes described as creating a “nameless” object and storing its reference in c. The object lives on the managed heap; c is a reference (typically on the stack if local).



Step-by-Step Solution:

Declaration: sample c; → declares a reference variable c.Instantiation: new sample(); → allocates a new object on the heap.Assignment: c = (that object reference).


Verification / Alternative check:
Printing ReferenceEquals(c, null) after assignment returns false; GC can collect the object if no references remain.



Why Other Options Are Wrong:
(a) implies the object gets the name sample; in fact, sample is the type name, not the object name. (c) and (e) are wrong because class objects are allocated on the managed heap in C#.



Common Pitfalls:
Thinking objects of reference types can be stack-allocated by size or that the object itself has an identifier beyond its reference(s).



Final Answer:
2, 4

More Questions from Classes and Objects

Discussion & Comments

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