Search code examples
c#genericsenumsextension-methodsgeneric-programming

How can we extend all enum type?


How can we extend all enum type?

I want to extend all enum type with a new method called "ToStringConstant". This method will return the integer value as String. Here is what I have so far, but compilator won't allow enum in the where clause.

    public static string ToStringConstant<T>(this T EnumVar) where T : enum
    {
        return ((int)EnumVar).ToString();
    }

Example :

public enum Example
{
    Example = 0
}

void Method()
{
    Example var =  Example.Example;
    var.ToString();//Return "Example"
    var.ToStringConstant();//Return "0"   
}

Solution

  • Don't make the method generic, just accept an Enum:

    public static string ToStringConstant(this Enum EnumVar)
    {
        return ((int)EnumVar).ToString();
    }
    

    On a side note, casting to long instead of int will ensure that the code functions regardless of the underlying type of the enumeration.