buunguyen / fasterflect

.NET Reflection Made Fast and Simple ⛺
https://www.nuget.org/packages/fasterflect/
Apache License 2.0
283 stars 55 forks source link

Oversight in MemberGetEmitter when dealing with enums #17

Open cbp123 opened 3 years ago

cbp123 commented 3 years ago

The relevant code is in MemberGetEmitter (and possibly elsewhere in the codebase):

        if (fieldInfo.DeclaringType.IsEnum)
          this.Generator.ldc_i4((int) fieldInfo.GetValue((object) fieldInfo.DeclaringType)).boxIfValueType(fieldInfo.FieldType);
        else
          this.Generator.ldfld(fieldInfo.IsStatic, fieldInfo).boxIfValueType(fieldInfo.FieldType);

A little known fact of C# is that enums can inherit from shorts, bytes and longs, e.g.

public enum MyEnum : short
{
  Foo = 1,
  Bar = 2
}

Atempting to get a field value for enum that inherits from something other than int32 causes the above code to crash with an InvalidCastException