#249 – Using a get Accessor to Clean up Property Data

It’s not always the case that when you read a property’s value, you want exactly the same value that you wrote to the property.

As an example, imagine that we have a Dog.ShowDogName property that lets us read/write our dog’s official “show dog” name.  Show dog names are titles, so each word should be capitalized.  For convenience, we’d like the client code to not worry about the capitalization, but have the class take care of it.

We store the property in its original non-capitalized state and then clean up the name by capitalizing it whenever the property is read.

        private string showDogName;
        public string ShowDogName
        {
            get
            {
                return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(showDogName);
            }

            set
            {
                showDogName = value;
            }
        }

Here’s an example of some client code using the new property:

            kirby.ShowDogName = "fitzgerald's rich socialite mister stinks-a-lot";

            // Fitzgerald's Rich Socialite Mister Stinks-A-Lot
            Console.WriteLine(kirby.ShowDogName);
Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: