#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