Tuesday, November 15, 2011

How to add methods to an enum in C#


The problem

In C#, enums are simple value types which just contain a bunch of constants. No other type of member can be included.

Given that C# was influenced by C and C++, this is no surprise as enums in those languages only contain constants as well. However, Java allows enums to include methods so how can we do something similar in C#? 

The solution

The answer is to use extension methods which were introduced in C# 3.0.

Here's an example where we (effectively) add some methods to a Colors enum.

using System;
public enum Colors
{
    White,
    Red,
    Blue,
    Green
}
// extension methods for the Colors enum
public static class ColorsExtensions
{
    public static bool IsWhite(this Colors c)
    {
        return c == Colors.White;
    }
    public static bool IsRedOrBlue(this Colors c)
    {
        return c == Colors.Red || c == Colors.Blue;
    }
}
class Test
{
    static void Main()
    {
        Colors c = Colors.Red;
        Console.WriteLine(c.IsWhite()); // False
        Console.WriteLine(c.IsRedOrBlue());  // True
        Console.ReadKey();
    }
}

No comments:

Post a Comment