C#.NET properties — To allow both assigning and printing acc.accountNo, how should Account.accountNo be declared?

C# Programming Properties Difficulty: Easy
Choose an option
  • A
    Declare accountNo with both get and set accessors.
  • B
    Declare accountNo with only get accessor.
  • C
    Declare accountNo with get, set and normal accessors.
  • D
    Declare accountNo with only set accessor.
  • E
    None of the above

Answer

Correct Answer: Declare accountNo with both get and set accessors.

Explanation

Introduction / Context:The sample code performs both a write and a read: acc.accountNo = 10; and Console.WriteLine(acc.accountNo);. Therefore, the property must support assignment and retrieval. This is a standard read–write property in C#.

Given Data / Assumptions:

  • Account class has a property named accountNo.
  • We want both setting and getting to compile and work.

Concept / Approach:A C# property that can be both read and assigned must include a get accessor (to return the value) and a set accessor (to accept a value via the implicit parameter value). Omitting either accessor would disable the corresponding operation.

Step-by-Step Solution:

Provide a backing field, for example: private int _accountNo;Declare property: public int accountNo { get { return _accountNo; } set { _accountNo = value; } }Use: acc.accountNo = 10; Console.WriteLine(acc.accountNo);

Verification / Alternative check:Compile with both accessors present and observe that both statements are valid. Remove get or set and see the relevant statement fail.

Why Other Options Are Wrong:

  • B: Read-only; assignment would fail.
  • C: “normal accessors” is not a C# concept; get/set already cover it.
  • D: Write-only; Console.WriteLine(acc.accountNo) would fail.
  • E: There is a correct solution (A).

Common Pitfalls:Confusing access modifiers (public/private) with accessors (get/set). You can also fine-tune with private set if external code should not assign.

Final Answer:Declare accountNo with both get and set accessors.

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