C#.NET — Consider the structure and usage below. Which statements are correct? struct Book { private string name; protected int totalpages; public Single price; public void Showdata() { Console.WriteLine(name + " " + totalpages + " " + price); } Book() { name = ""; totalpages = 0; price = 0.0f; } } Book b = new Book(); Evaluate the following claims: 1) We cannot declare totalpages as protected. 2) We cannot declare name as private. 3) We cannot define a zero-argument constructor inside a struct. 4) We cannot declare price as public. 5) We can define a Showdata() method inside a struct.

Difficulty: Medium

Correct Answer: 1, 3, 5

Explanation:


Introduction / Context:
Structs in C# are value types with specific rules. Some class-like features are allowed, while others are restricted, especially regarding inheritance and constructors.



Given Data / Assumptions:

  • The struct declares private, protected, and public members, plus a parameterless constructor and a method.
  • We judge each claim for correctness.


Concept / Approach:
Structs cannot be inherited; therefore, a protected accessibility level (which relies on inheritance) is not meaningful and is disallowed. Historically, user-defined parameterless constructors in structs were not allowed; the runtime provides a default parameterless constructor that zero-initializes fields. Methods are allowed in structs. Private fields and public fields are also allowed.



Step-by-Step Solution:

1) True — protected is illegal in structs.2) False — private fields are permitted inside structs.3) True — defining a user zero-arg constructor in a struct is not allowed in traditional C# versions (the runtime supplies one).4) False — public fields are allowed; though properties are typically preferred.5) True — methods like Showdata() are allowed within structs.


Verification / Alternative check:
Attempting to compile the sample as-is results in errors for protected and the explicit parameterless constructor.



Why Other Options Are Wrong:

  • A/C/D: Each includes at least one false statement (2 or 4).
  • None of these: Incorrect because 1, 3, and 5 are true.


Common Pitfalls:
Assuming class rules apply verbatim to structs; they do not due to lack of inheritance.



Final Answer:
1, 3, 5

More Questions from Structures

Discussion & Comments

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