Skip to content
This repository was archived by the owner on Sep 25, 2026. It is now read-only.
This repository was archived by the owner on Sep 25, 2026. It is now read-only.

Don't consider static field on bases to be in hierarchy #2020

Closed

Description

@MichalStrehovsky

As I was experimenting with dotnet/runtime#52535, I found out the reflection stack doesn't consider inherited static fields to be visible on the current type (typeof(Derived).GetField("SomeFieldFromBase", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) will not see the field on the base type unless it's an non-private instance field).

We can use this to restrict this search and allow more trimming:

https://github.com/mono/linker/blob/fafb6cf6a385a8c753faa174b9ab7c3600a9d494/src/linker/Linker.Dataflow/DynamicallyAccessedMembersBinder.cs#L156-L190

Activity

  1. MichalStrehovsky commented on May 10, 2021

    @MichalStrehovsky
    MemberAuthor
  2. vitek-karas commented on May 11, 2021

    @vitek-karas
    Member

    I think it's important to note that this is only true if the call didn't specify BindingFlags.FlattenHierarchy.

    using System;
    using System.Reflection;
    
    interface IFace
    {
        public static int PublicStaticOnInterface = 0;
    
        private static int PrivateStaticOnInterface = 0;
    }
    
    class Base
    {
        public static int PublicStaticOnBase = 0;
        public int PublicInstanceOnBase = 0;
        static int PrivateStaticOnBase = 0;
        int PrivateInstanceOnBase = 0;
    }
    class Program : Base, IFace
    {
        static void Main(string[] args)
        {
            foreach (var f in typeof(Program).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) Console.WriteLine(f);
        }
    }

    This prints out:

    Int32 PublicInstanceOnBase
    Int32 PublicStaticOnBase
    Int32 PublicStaticOnInterface
  3. MichalStrehovsky commented on May 11, 2021

    @MichalStrehovsky
    MemberAuthor

    Let's close since dotnet/runtime#102525 tracks the actual work needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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