#247 – Implementing a Write-Only Property

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
                barkPassword = value;

        // Bark method also sets lastBarked
        public void SecureBark(string password)
            if (password == barkPassword)
                Console.WriteLine("{0}: Woof!", Name);
                Console.WriteLine("Not allowed to bark");

Here’s how we might use the new property:

            kirby.BarkPassword = "flotsam62!";


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: