I have a class derived from base class which has a private field.
How can I get the BaseType field value?
public class SuperClass : BaseClass
{
}
public class BaseClass
{
private object theField;
}
I have the SuperClass instance and the code should be something like:
var baseType = super.GetType().BaseType;
var fieldInfo = baseType.GetField("theField", BindingFlags.NonPublic | BindingFlags.Instance);
Now how can I get the value from fieldInfo? Or my approach is wrong?
Use FieldInfo.GetValue
Incidentally you don’t need
super.GetType– you can just do:Equally, since you know the base type – it’s possibly marginally quicker to do
Update
I used
thisbecause your question implies that the code you’ve written is part ofSuperClassbecause you have written (despite it not being valid C#):If that’s not the case, and you have an instance of
SuperClassthen this will do:I would actually strongly recommend against using
obj.GetType().BaseType– because your reflection will immediately break if you choose to inject a base betweenSuperClassandBaseClass; whereas usingtypeof(BaseClass)won’t – unless you actually removeBaseClassfromSuperClass‘s inheritance tree.