#813 – Defining an Extension Method for an Enumerated Type

In addition to other types, you can extend the functionality of an enumerated type using extension methods.

Below is an extension method that extends the DayOfWeek enumerated type.

        public static string Activity(this DayOfWeek day)
        {
            string activity = "";

            switch (day)
            {
                case DayOfWeek.Sunday:
                    activity = "Reading paper";
                    break;
                case DayOfWeek.Monday:
                    activity = "Grumbling";
                    break;
                case DayOfWeek.Tuesday:
                    activity = "Eating tacos";
                    break;
                case DayOfWeek.Wednesday:
                    activity = "Reading";
                    break;
                case DayOfWeek.Thursday:
                    activity = "Cursing";
                    break;
                case DayOfWeek.Friday:
                    activity = "Celebrating";
                    break;
                case DayOfWeek.Saturday:
                    activity = "Hiking";
                    break;
            }

            return activity;
        }
    }

We can now call the Activity method on any variable or constant whose type is DayOfWeek.

            DayOfWeek today = DayOfWeek.Thursday;
            Console.WriteLine(today.Activity());

            Console.WriteLine(DayOfWeek.Friday.Activity());

813-001

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.

2 Responses to #813 – Defining an Extension Method for an Enumerated Type

  1. Alian says:

    Very interesting sample. This blog is one of my favorites.

  2. Mourad Barakat says:

    Nice explanation. Thanks you Sean!

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: