#247 – Implementing a Write-Only Property
February 19, 2011 Leave a comment
You implement a write-only property in a class by implementing the set accessor, but not the get accessor. This will allow client code to write the property’s value, but not read the current value.
Below is an example of a write-only property for the Dog class. The BarkPassword property can be written to, but not read back. The class then uses the internal value of BarkPassword in the SecureBark method, to verify that the dog is allowed to bark.
// Internal storage of secret name private string barkPassword; // Public property, write-only public string BarkPassword { set { barkPassword = value; } } // Bark method also sets lastBarked public void SecureBark(string password) { if (password == barkPassword) Console.WriteLine("{0}: Woof!", Name); else Console.WriteLine("Not allowed to bark"); }
Here’s how we might use the new property:
kirby.BarkPassword = "flotsam62!"; kirby.SecureBark("notthepassword");