C# Reflection – Get field values from a simple class

Once fixed to get rid of the errors (lacking a semi-colon and a bad variable name), the code you’ve posted does work – I’ve just tried it and it showed the names and values with no problems.

My guess is that in reality, you’re trying to use fields which aren’t public. This code:

FieldInfo[] fields = data.GetType().GetFields();

… will only get public fields. You would normally need to specify that you also want non-public fields:

FieldInfo[] fields = data.GetType().GetFields(BindingFlags.Public | 
                                              BindingFlags.NonPublic | 
                                              BindingFlags.Instance);

(I hope you don’t really have public fields, after all…)

Leave a Comment