user16889964
user16889964

Reputation:

Is enum to int unboxing?

enum Season { spring, summer, fall, winter }
int a = (int)Season.spring;

Is this a unboxing or just a normal casting? If this is a unboxing, could you explain why? I thought this is just a normal casting because 'enum' and 'int' is both a value-type data.

Upvotes: 2

Views: 1083

Answers (1)

Charlieface
Charlieface

Reputation: 72087

As documented in ECMA-334 11.3.3, C# defines a conversion to and from an enum type and its underlying type:

However, this does not specify whether or not it is an unboxing conversion. That could be deduced, though, from the fact that both the enum and the integer are value-types, therefore no unboxing is involved.

ECMA-335, which defines the CLR, makes it more clear that an enum is not just convertible to an integer, it actually is the integer, there is no conversion done at all:

14.3 Enums

For binding purposes (e.g., for locating a method definition from the method reference used to call it) enums shall be distinct from their underlying type. For all other purposes, including verification and execution of code, an unboxed enum freely interconverts with its underlying type. Enums can be boxed (§13) to a corresponding boxed instance type, but this type is not the same as the boxed type of the underlying type, so boxing does not lose the original type of the enum.

Upvotes: 5

Related Questions