0

I've got the following class:

public sealed class ImmutableObject {

         public readonly int ic;

         public ImmutableObject(int value) {
             ic = value;
         }
}

Then I created a method that tries to obtain reflection informations by this class:

public static void infosByImmutableObject() {
         ImmutableObject iobj = new ImmutableObject(1);

         Console.WriteLine(iobj.ic);

         Type typeIobj = iobj.GetType();

         PropertyInfo infos = typeIobj.GetProperty("ic");

}

I can't understand why, although ic is public, infos remains null, and if I try with Type.GetProperties the result array has zero elements. I noticed that, without the readonly modifier, GetProperties("ic") returns. How a public field is seen by GetProperty() when the readonly is present?

zappasan
  • 82
  • 10

1 Answers1

3

ic is not a property, it's a field. You should use GetField or GetFields to retrieve a FieldInfo object for it:

FieldInfo infos = typeIobj.GetField("ic");
Debug.Assert(infos!=null);

Fields and properties are different types of members in .NET. In general, properties are considered a part of a class's interface while fields are considered part of its implementation.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thank you very much. I wasn't aware of this distinction. For duty I attach this [answer](http://stackoverflow.com/a/7975677/3544562) – zappasan Aug 12 '15 at 10:26
  • For extra fun, see what happens if you try to set a `readonly` field through reflection. – Jon Hanna Aug 12 '15 at 10:58