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

C# Programming Classes and Objects Difficulty: Easy
Choose an option
  • A
    It will create an object called sample.
  • B
    It will create a nameless object of the type sample.
  • C
    It will create an object of the type sample on the stack.
  • D
    It will create a reference c on the stack and an object of the type sample on the heap.
  • E
    It will create an object of the type sample either on the heap or on the stack depending on the size of the object.

Answer

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

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