Bird
Raised Fist0

Identify the error in this C# code snippet:

medium📝 Debug Q14 of Q15
C Sharp (C#) - Properties and Encapsulation

Identify the error in this C# code snippet:

class Account {
    private string _pin;
    public string Pin {
        get { return _pin; }
        set { _pin = value; }
    }
}

var acc = new Account();
acc.Pin = "1234";
Console.WriteLine(acc.Pin);

The goal is to make Pin write-only.

AThe private field _pin should be public.
BThe set accessor should return a value.
CThe property has both get and set accessors, so it is not write-only.
DThe property should be static.
Step-by-Step Solution
Solution:
  1. Step 1: Check property accessors

    The property has both get and set accessors, allowing reading and writing.
  2. Step 2: Understand write-only requirement

    Write-only properties must have only a set accessor and no get accessor.
  3. Final Answer:

    The property has both get and set accessors, so it is not write-only. -> Option C
  4. Quick Check:

    Write-only = set only, no get [OK]
Quick Trick: Write-only means no get accessor allowed [OK]
Common Mistakes:
MISTAKES
  • Leaving both get and set for write-only
  • Changing field visibility instead of property
  • Expecting set to return a value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes