Reflection API Incorrectly Boxes (U)IntPtr Constants as (U)Int32 #104270
Open
Description
opened on Jul 2, 2024
Description
The reflection API is expected to box constant literal fields of type (U)IntPtr as their correct types. However, when using reflection to retrieve the value of these constants, they are being boxed as (U)Int32 instead of (U)IntPtr.
Reproduction Steps
public enum E {
V = 42,
}
internal class Program {
public const UIntPtr A = 3;
public const IntPtr B1 = -5;
public const E C = E.V;
public const long D = 1;
static void Main(string[] args) {
DumpConstLiteralByReflection("UIntPtr", nameof(A));
DumpConstLiteralByReflection("IntPtr", nameof(B1));
DumpConstLiteralByReflection("enum E", nameof(C));
DumpConstLiteralByReflection("long", nameof(D));
static void DumpConstLiteralByReflection(string label, string fieldName) {
Console.WriteLine($@"{label}:");
Console.WriteLine($@" Field type: {typeof(Program).GetField(fieldName)!.FieldType}");
var o = typeof(Program).GetField(fieldName)!.GetValue(null)!;
Console.WriteLine($@" Value type: {o.GetType()}");
Console.WriteLine($@" Value: {o:D}");
Console.WriteLine();
}
}
}
Expected behavior
UIntPtr:
Field type: System.UIntPtr
Value type: System.UIntPtr
Value: 3
IntPtr:
Field type: System.IntPtr
Value type: System.IntPtr
Value: -5
enum E:
Field type: E
Value type: E
Value: 42
long:
Field type: System.Int64
Value type: System.Int64
Value: 1
Actual behavior
UIntPtr:
Field type: System.UIntPtr
Value type: System.UInt32
Value: 3
IntPtr:
Field type: System.IntPtr
Value type: System.Int32
Value: -5
enum E:
Field type: E
Value type: E
Value: 42
long:
Field type: System.Int64
Value type: System.Int64
Value: 1
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
This issue may present a theoretical security risk, although the practical threat is likely negligible.
Activity