Reputation: 82
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?
Upvotes: 0
Views: 400
Reputation: 131228
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.
Upvotes: 3