I feel that the 1st argument of Enum.Format() is a bit redundant

74 views Asked by At

I've got the code blow:

enum Days
{
    day1,
    day2,
    day3
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Enum.Format(typeof(Days), Days.day2, "D"));
    }
}

I feel that 1st argument of Enum.Format() is redundant: because the 2nd argument already specified the type of Enum, so compiler will have the information that the type of "day2" is "Days". Then why compile doesn't deduce that the 1st argument to be "typeof(Days)" for it self, why I have to specify it?

In other words, I mean, if .net function of Enum.Format only have 2 arguments, why can't it be? Type can be know from the value argument.

1

There are 1 answers

0
xanatos On BEST ANSWER

Because you can use the underlying type of the enum in the value parameter, like:

public enum MyEnum
{
    Foo = 1
}

string str = Enum.Format(typeof(MyEnum), 1, "G"); // Foo

But note that:

public enum MyEnum : long
{
    Foo = 1
}

string str = Enum.Format(typeof(MyEnum), 1L, "G");

As I've written, you have to use the underlying type! So in this case, long.

Very indirectly this is spelled out in Enum.Format:

ArgumentException: The type of value is not an underlying type of enumType.

So implicitly, if value is of the underlying type of enumType, then there is no exception and some result is returned.