#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);
Advertisements

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: