Search code examples
c#system.reflection

How to get readonly field value from base generic abstract class


I would like to retrieve readonly field value _classC from base generic abstract class Base<A, B> .

What I have tried

FieldInfo.GetValue must be used certainly, but I can't guess the right parameter.

Thought the instance of the derived class would be okay.

var derived = new Derived();
var baseType = typeof(Base<,>);

var classCField = baseType
  .GetField("_classC", BindingFlags.NonPublic 
    | BindingFlags.Static 
    | BindingFlags.Instance 
    | BindingFlags.FlattenHierarchy);

classCField.GetValue(derived);

The error I get

InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.

Is that even possible?

Type definitions

public interface IBase<A, B>
    where A : class
    where B : class, new()
{
    
}

public class ClassD
{
    
}

public class ClassC
{
    
}

public abstract class Base<A, B> : IBase<A, B>
    where A : class
    where B : class, new()
    {
        private readonly ClassC _classC = new ClassC();
    }

public class Derived : Base<ClassC, ClassD>
{
}

Solution

  • do this :

    var field = typeof(Derived).BaseType.GetField("_classC", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
    var value = field.GetValue(derived);