-1

I've read many opinions that public fields are evil, public properties are by designed to be public and we can do super great things with setters and getters etc.

My understanding is, although minimal, readonly fields are a performance hit (and, related to performance or not, I know both FXCop and Resharper prompt me to use readonly where ever possible).

I know we can't have a readonly property in .NET but, are readonly public fields still evil?

Dave
  • 8,163
  • 11
  • 67
  • 103
  • 2
    "I know we can't have a readonly property in .NET" - in what way? You can have a property which doesn't have a setter... – Jon Skeet Dec 12 '13 at 14:42
  • @JonSkeet, are you saying that `public string s {get...}` is treated the same way as `private readonly string s`? If so, I'll just remove my question – Dave Dec 12 '13 at 14:43
  • 2
    Well that's not valid code to start with. But you could have `private readonly string name; public string Name { get { return name; } }` which is a readonly property backed by a readonly field. – Jon Skeet Dec 12 '13 at 14:44
  • 1
    @DaveRook: No, a readonly field can only be assigned once in a constructor or a variable initializer whereas the (private) backing field of a property without a public setter can be assigned as often as you want (from within this class). – Tim Schmelter Dec 12 '13 at 14:46
  • This question is more or less answered before please refer this [link][1] [1]: http://stackoverflow.com/questions/3917796/how-to-implement-a-read-only-property – Siddartha Dec 12 '13 at 15:02

1 Answers1

2

One of the reasons why public fields are evil is that if 100 other assemblies are compiled against that field, and later you decide to replace it with a public property (to include validation, etc), all those assemblies will have to be recompiled as well.

So, it really doesn't matter whether the field is readonly or not - public fields are still evil.

dcastro
  • 66,540
  • 21
  • 145
  • 155