M.kazem Akhgary
M.kazem Akhgary

Reputation: 19169

Is enum to Enum boxing or just type casting

I'm wondering if casting to Enum will box enum or not

So should I write expression bodied member to reduce size of my objects.

public Fruit FruitType => (Fruit) Type; // unboxing?
public override Enum Type => (Fruit) (Data[0] & 0xF0); // boxing?

Or have property to prevent boxing and unboxing?

public Fruit FruitType => (Fruit) (Data[0] & 0xF0);
public override Enum Type { get; } = (Fruit) (Data[0] & 0xF0); // assigned once.

Assuming I have thousands of instances. and this property is used about 60 thousand times.

Upvotes: 3

Views: 1043

Answers (1)

Heinzi
Heinzi

Reputation: 172390

Yes, the value is boxed.

Section 4.3.1 "Boxing conversions" of the C# spec states:

A boxing conversion permits a value-type to be implicitly converted to a reference-type. The following boxing conversions exist:

[...]

  • From any enum-type to the type System.Enum.

[...]

Upvotes: 4

Related Questions