-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Closed
Milestone
Description
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.
Wraith2