C#.NET structs — Which of the following statements are correct? 1) A struct can contain properties. 2) A struct can contain constructors. 3) A struct can contain protected data members. 4) A struct cannot contain methods. 5) A struct cannot contain constants.

Difficulty: Easy

Correct Answer: 1, 2

Explanation:


Introduction / Context:
Value types (structs) in C#.NET support a rich set of members, though they have some limitations compared to classes. This item asks which features are permitted in a struct definition.



Given Data / Assumptions:

  • We consider typical C# (struct as a value type, sealed by nature).
  • We evaluate five claims about what a struct may contain.


Concept / Approach:
Structs can contain fields, properties, methods, operators, events, indexers, and constructors. They cannot declare a protected member because structs cannot be inherited. They can define constructors, but historically user-defined parameterless constructors were disallowed until newer language versions; parameterized constructors are always allowed. Structs can include constants (const members).



Step-by-Step Solution:

1) Properties → allowed → true.2) Constructors → allowed (at least parameterized) → true.3) Protected data members → not allowed because structs are non-inheritable → false.4) “Cannot contain methods” → incorrect; methods are permitted → false.5) “Cannot contain constants” → incorrect; const is allowed → false.


Verification / Alternative check:
Create a sample struct with a property, a parameterized constructor, a method, and a const; it compiles. Attempt to mark a member protected; the compiler rejects it.



Why Other Options Are Wrong:

  • 3, 4 and 3, 5: Depend on invalid claims about protected, methods, or constants.
  • 1, 2, 4: Includes the false statement 4.
  • None of these: Not correct because 1 and 2 are valid.


Common Pitfalls:
Assuming structs are too restricted; they are feature-rich but simply non-inheritable.



Final Answer:
1, 2

More Questions from Structures

Discussion & Comments

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