2

Basically, I have the following:

protected static readonly FieldInfo SpecialField = FindSpecialField();

FxCop is complaining to me though that I should not make a field readonly if it is mutable because the members can be changed. Are FieldInfo and PropertyInfo immutable or mutable. Basically, can I suppress this message?

michael
  • 14,844
  • 28
  • 89
  • 177

3 Answers3

2

FieldInfo itself looks immutable, but derviations of it may or may not be. For example, the FieldBuilder can be modified. Same holds for PropertyInfo.

So, if you know it's always a FieldInfo obtained from reflection, then chances are you will be safe.

CodeNaked
  • 40,753
  • 6
  • 122
  • 148
1

I would say they are Immutable. There are no members to change the state of instances of FieldInfo and PropertyInfo. The SetValue() method changes the value of the instance (or the class's static members) to which the Field/Property belongs to but not the FieldInfo/PropertyInfo itself.

Bala R
  • 107,317
  • 23
  • 199
  • 210
1

While I've never seen one that I've known to be mutable, those are base classes, and who knows what the derived classes could be like.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Well, since it is a static readonly I have to set it inside that same class, which means I control the implementation. I just want to what FxCop pointed out, which is... readonly on a mutable type is dumb because you can just change the members from within that instance. But in this case you're saying FieldInfo is immutable, so I'm safe... short of someone shooting themselves in the foot by reflecting in and changing members they shouldn't be. – michael Jun 21 '11 at 20:04