Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
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 @@ -311,6 +311,22 @@ protected override void GetMetadataDependenciesDueToReflectability(ref Dependenc
}
}

if (type.IsArray)
{
// Array.Initialize needs the default constructor of the element type to be reflectable
// for value types with a public parameterless constructor.
TypeDesc elementType = ((ArrayType)type).ParameterType;
if (elementType.IsValueType)
{
MethodDesc defaultConstructor = elementType.GetDefaultConstructor();
if (defaultConstructor is not null && !IsReflectionBlocked(defaultConstructor))
{
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectedMethod(defaultConstructor.GetCanonMethodTarget(CanonicalFormKind.Specific)), "Array.Initialize needs default constructor");
}
}
}

MetadataType mdType = type as MetadataType;
ModuleDesc module = mdType?.Module;
if (module != null && !_rootEntireAssembliesExaminedModules.Contains(module))
Expand Down
32 changes: 32 additions & 0 deletions src/tests/nativeaot/SmokeTests/Reflection/Reflection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ private static int Main()
TestGenericAttributesOnEnum.Run();
TestLdtokenWithSignaturesDifferingInModifiers.Run();
TestActivatingThingsInSignature.Run();
TestArrayInitialize.Run();
TestDelegateInvokeFromEvent.Run();

return 100;
Expand Down Expand Up @@ -3004,6 +3005,37 @@ public struct MyStruct;
public struct MyArrayElementStruct;
}

class TestArrayInitialize
{
static int s_constructorCallCount = 0;

public struct ValueTypeWithConstructor
{
public ValueTypeWithConstructor()
{
s_constructorCallCount++;
}
}

[MethodImpl(MethodImplOptions.NoInlining)]
static Array AllocateArray() => new ValueTypeWithConstructor[3];

public static void Run()
{
Console.WriteLine(nameof(TestArrayInitialize));

s_constructorCallCount = 0;

// Create an array and call Initialize
var array = AllocateArray();
array.Initialize();

// Verify that the constructor was called for each element
if (s_constructorCallCount != 3)
throw new Exception($"Expected constructor to be called 3 times, but was called {s_constructorCallCount} times");
}
}

class TestDelegateInvokeFromEvent
{
class MyClass
Expand Down
Loading