Given this class
class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
ge
You can access any private field of an arbitrary type with code like this:
Foo foo = new Foo();
string c = foo.GetFieldValue("_bar");
For that you need to define an extension method that will do the work for you:
public static class ReflectionExtensions {
public static T GetFieldValue(this object obj, string name) {
// Set the flags so that private and public fields from instances will be found
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var field = obj.GetType().GetField(name, bindingFlags);
return (T)field?.GetValue(obj);
}
}