简体   繁体   中英

Enum to int, why use type cast to int rather than Convert.ToInt32(Enum)?

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 ?

By default, enums inherit from int , ie 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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM