Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change ParameterDefaultValue to use GetUninitializedObject instead of Activator.CreateInstance #47722

Merged
merged 2 commits into from
Feb 5, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

#if NETFRAMEWORK || NETSTANDARD2_0
using System.Runtime.Serialization;
#else
using System.Runtime.CompilerServices;
#endif

namespace Microsoft.Extensions.Internal
{
internal class ParameterDefaultValue
{
private static readonly Type _nullable = typeof(Nullable<>);

public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
{
bool hasDefaultValue;
Expand All @@ -39,21 +43,27 @@ public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defau
defaultValue = parameter.DefaultValue;
}

bool isNullableParameterType = parameter.ParameterType.IsGenericType &&
parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);

// Workaround for https://github.com/dotnet/runtime/issues/18599
if (defaultValue == null && parameter.ParameterType.IsValueType)
if (defaultValue == null && parameter.ParameterType.IsValueType
pakrym marked this conversation as resolved.
Show resolved Hide resolved
&& !isNullableParameterType) // Nullable types should be left null
{
defaultValue = CreateValueType(parameter.ParameterType);
}

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern",
Justification = "CreateInstance is only called on a ValueType, which will always have a default constructor.")]
static object? CreateValueType(Type t) => Activator.CreateInstance(t);
Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")]
static object? CreateValueType(Type t) =>
#if NETFRAMEWORK || NETSTANDARD2_0
FormatterServices.GetUninitializedObject(t);
#else
RuntimeHelpers.GetUninitializedObject(t);
#endif

// Handle nullable enums
if (defaultValue != null &&
parameter.ParameterType.IsGenericType &&
parameter.ParameterType.GetGenericTypeDefinition() == _nullable
)
if (defaultValue != null && isNullableParameterType)
{
Type? underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
if (underlyingType != null && underlyingType.IsEnum)
Expand Down