Search code examples
c#enumsgarbage-collectiongarbage

Enum Extension generating garbage


I have the following;

public static bool Has<T>(this System.Enum type, T value) where T : struct
{
    return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);
}

For some reason, calling this extension method is generating garbage, and I simply can't see why. Everything here is struct or values. Where is that unseen garbage? Is there some not-so-obvious boxing going on? Is there a better way to do this extension method?


Solution

  • Casting to ValueType effectively boxes the object (note that ValueType, while the "base class for value types", is a class), and then the cast to int unboxes it. This will also fail if the underlying type of the enum happens to be something other than Int32, which is also possible.

    You should be able to use Enum.HasFlag to accomplish this same functionality without a custom method.