C# Programming - Structures - Discussion

Discussion Forum : Structures - General Questions (Q.No. 12)
12.
Which of the following statements is correct about the C#.NET code snippet given below?
struct Book
{
    private String name; 
    private int noofpages; 
    private Single price;
}
Book b = new Book();
The structure variable b will be created on the heap.
We can add a zero-argument constructor to the above structure.
When the program terminates, variable b will get garbage collected.
The structure variable b will be created on the stack.
We can inherit a new structure from struct Book.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
2 comments Page 1 of 1.

Nicholas Mahbouby said:   10 years ago
Structs types are stored on the stack only when declared as local variables of a method or members of another struct. When declared as members of a class they will be created on the heap with that class.

From the code snippet one can assume that the variable b is a member variable, since Book is declared just before it, which would give a compiler error in a method. One can also assume b is a member of a class, since it is initialized inline, which would give a compiler error inside a struct. So in this case b would be created on the heap with it's containing class. Answer D is wrong.

K reddy kishore said:   1 decade ago
Because of structure value type that stores values in stack only.

Post your comments here:

Your comments will be displayed after verification.