1

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"   
}
AXMIM
  • 2,424
  • 1
  • 20
  • 38
  • possible duplicate of [Create Generic method constraining T to an Enum](http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum) – juharr Mar 19 '15 at 19:27
  • possible duplicate of [How to add extension methods to Enums](http://stackoverflow.com/questions/15388072/how-to-add-extension-methods-to-enums) – Austin Hanson Mar 19 '15 at 19:27

1 Answers1

3

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Note that this can fail for enum types which don't have `int` as their underlying types. (It's a problem in the OP's code, but just something to be aware of.) – Jon Skeet Mar 19 '15 at 19:29
  • @JonSkeet Well, it'll work fine for enums with byte/short or any other smaller integer types. It'll break on `long` unless you cast to `long` instead of `int`. – Servy Mar 19 '15 at 19:31
  • For some weird reason, compilator say "Cannot convert type 'System.Enum' to 'int'". I will use Convert.ToDouble instead... – AXMIM Mar 19 '15 at 19:45
  • 1
    @AXMIM You should use `Convert.ToInt64` as it is an integer value, not a floating point value. – Servy Mar 19 '15 at 19:50