thing - a field that is not a property. You should use the GetField method instead of GetProperty . Another problem is that you are looking at typeof(T) . You should look for the field in typeof(Base) .
All function must be changed to
public T GetAttribute<T>(string _name) { return (T)GetType().GetField(_name).GetValue(this); }
If you want to have an extension method to get the value of a type field, you can use this
public static class Ex { public static TFieldType GetFieldValue<TFieldType, TObjectType>(this TObjectType obj, string fieldName) { var fieldInfo = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); return (TFieldType)fieldInfo.GetValue(obj); } }
Use it like
var b = new Base(); Console.WriteLine(b.GetFieldValue<string, Base>("thing"));
Using BindingFlags will help you get the value of a field, even if it is a private or static field.
source share