1

Been looking at the Enum to int qa's, There are plenty of type casting of (int)Enum , however I couldn't find any answers that suggests use of Convert.ToInt32(Enum).

Is there any reason for preferring typecast over using Convert.ToInt32 ?

LUIS PEREIRA
  • 478
  • 4
  • 20
jimjim
  • 2,414
  • 2
  • 26
  • 46

1 Answers1

3

By default, enums inherit from int, i.e. behind the scenes it is:

enum Foo : int
    {
        A,
        B
    }

In C#, there is no difference between Int32 and int. So using Convert.ToInt32(Foo.A) is a bit redundant, since performing (int)Foo.A will suffice. Personally, (int)Foo.A also reads much better. Note, you would only really have to watch this in situations where you defined your enum like so:

enum Foo : long
    {
       A,
       B
    }
Leigh Shepperson
  • 1,043
  • 5
  • 13