Muokkaa

Jaa


How to create a new method for an enumeration (C# Programming Guide)

You can use extension methods to add functionality specific to a particular enum type.

Example

In the following example, the Grades enumeration represents the possible letter grades that a student may receive in a class. An extension method named Passing is added to the Grades type so that each instance of that type now "knows" whether it represents a passing grade or not.

using System;

namespace EnumExtension
{
    // Define an extension method in a non-nested static class.
    public static class Extensions
    {
        public static Grades minPassing = Grades.D;
        public static bool Passing(this Grades grade)
        {
            return grade >= minPassing;
        }
    }

    public enum Grades { F = 0, D=1, C=2, B=3, A=4 };
    class Program
    {
        static void Main(string[] args)
        {
            Grades g1 = Grades.D;
            Grades g2 = Grades.F;
            Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
            Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");

            Extensions.minPassing = Grades.C;
            Console.WriteLine("\r\nRaising the bar!\r\n");
            Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
            Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");
        }
        /* Output:
            First is a passing grade.
            Second is not a passing grade.

            Raising the bar!

            First is not a passing grade.
            Second is not a passing grade.
        */
    }
}

Note that the Extensions class also contains a static variable that is updated dynamically and that the return value of the extension method reflects the current value of that variable. This demonstrates that, behind the scenes, extension methods are invoked directly on the static class in which they are defined.

See also