This is very similar to dotnet/runtime#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 https://github.com/dotnet/coreclr/pull/17877.)
Are you planning to return null in this case?
@AtsushiKan: That is a good question. A case can be made for either null or (TEnum)0.
I tend towards null because the default value of all other types is null in this scenario involving generics. Perhaps better if enums don't become the sole exception.
What do you think?
We went with null for DateTime (and by inference, value types in general) before, right?
Also, if you replace typeof(AttributeTargets) with typeof(ArbitraryStruct) in your example, null comes back today.
So we'll be consistent by returning null for enums too.
Ok, feel free to make a PR for CoreCLR. I've identified a similar issue in Project N so I'll make the fix for that concurrently. Thanks for finding this!
Most helpful comment
Ok, feel free to make a PR for CoreCLR. I've identified a similar issue in Project N so I'll make the fix for that concurrently. Thanks for finding this!