#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
        {
            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");

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers