Skip to content

[NativeAOT] The Finalize method is not preserved via reflection #72494

@LakshanF

Description

@LakshanF

NativeAOT does not seem to keep the Finalize method.

Repro: Run the below code under AOT
Current Behavior: The program throws

Instantiated object
Finalize
Invoking Finalize
Unhandled Exception: EETypeRva:0x00347398(System.Reflection.MissingRuntimeArtifactException): This object cannot be invoked because no code was generated for it: 'MyApp.ExampleClass.Finalize()'.
   at System.Reflection.Runtime.MethodInfos.RuntimeNamedMethodInfo`1.GetUncachedMethodInvoker(RuntimeTypeInfo[], MemberInfo) + 0x113
   at System.Reflection.Runtime.MethodInfos.RuntimeMethodInfo.get_MethodInvoker() + 0xa1
   at System.Reflection.Runtime.MethodInfos.RuntimeMethodInfo.Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) + 0x34
   at MyApp.Program.M1() + 0x81
   at test1!<BaseAddress>+0x1f7570

Expected: The code to run without problems

using System.Reflection;
using System.Diagnostics;

namespace MyApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            M1();
        }

        public static void M1()
        {
            ExampleClass ex = new ExampleClass();
            MethodInfo method = typeof(ExampleClass).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance);
            Debug.Assert(method!=null);
            Console.WriteLine(method.Name);
            Console.WriteLine("Invoking Finalize");
            method.Invoke(ex, null);
        }

    }

    public class ExampleClass
    {
        public ExampleClass()
        {
            Console.WriteLine("Instantiated object");
        }

        ~ExampleClass()
        {
            Console.WriteLine("Finalizing object");
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions