Skip to content

Reflection: ParameterInfo.DefaultValue can throw FormatException for enum parameters #26108

@stakx

Description

@stakx

This is very similar to #24574, but it turns out the problem doesn't just occur with System.DateTime (now fixed) but can happen with enums, too:

using System;

public class Program
{
    public void Method<T>(T arg = default(T)) { }

    public static void Main(string[] args)
    {
        var method = typeof(Program).GetMethod("Method").MakeGenericMethod(typeof(AttributeTargets));
        var argParameter = method.GetParameters()[0];
        Console.WriteLine(argParameter.DefaultValue);
    }
}
System.FormatException: Encountered an invalid type for a default value.
   at System.Reflection.MdConstant.GetValue(MetadataImport scope, Int32 token, RuntimeTypeHandle fieldTypeHandle, Boolean raw)
   at System.Reflection.RuntimeParameterInfo.GetDefaultValueInternal(Boolean raw)
   at System.Reflection.RuntimeParameterInfo.GetDefaultValue(Boolean raw)
   at Program.Main(String[] args)

(Default values for enums typically get recorded as metadata constants of the enums' underlying type. However, the use of C# default in a generics scenario leads to a null reference being used instead, and MdConstant currently can't deal with this corner case.)

May I send a PR with a fix? (Will look very similar to dotnet/coreclr#17877.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions