Skip to content

ParameterInfo.DefaultValue returns the raw value if the enum is nullable #12924

@jnm2

Description

@jnm2

Given the following method parameters, the first ParameterInfo's DefaultValue returns SomeEnum.A, unlike the RawDefaultValue parameter. The second ParameterInfo's DefaultValue returns 0, just like the RawDefaultValue parameter:

enum SomeEnum { A, B }

class Foo
{
    public void Bar(SomeEnum x = SomeEnum.A, SomeEnum? y = SomeEnum.A)
    {
    }
}

public static class Program
{
    public static void Main()
    {
        foreach (var parameter in typeof(Foo).GetMethod(nameof(Foo.Bar)).GetParameters())
        {
            var defaultValue = parameter.DefaultValue;
            Console.WriteLine($"{defaultValue} ({defaultValue.GetType()})");
        }
    }
}

Output:

A (SomeEnum)
0 (System.Int32)

To work around the problems this was causing, you can replace all calls to ParameterInfo.DefaultValue with a call to this method:

private static object GetDefaultValue(ParameterInfo parameter)
{
    if (parameter.DefaultValue != null)
    {
        var underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);

        if (underlyingType != null && underlyingType.IsEnum)
        {
            return Enum.ToObject(underlyingType, parameter.DefaultValue);
        }
    }

    return parameter.DefaultValue;
}

Someone suggested that I file this in case this is something you would consider changing in a future major version.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions