3 ms·
And when you want to make Foo no longer a primary value and instead calculated from some other field? When you want to add logging to every change of Foo? Every
by InclinedPlane 9y ago
And when you want to make Foo no longer a primary value and instead calculated from some other field? When you want to add logging to every change of Foo? Every access? When you want to switch to having Foo's value come from a database? Web service?
- flukus 9y agoThen I'd change it to a property and recompile. If it's value comes from the database or a web service then nothing has to change, whatever is calling the service will invoke the constructor as always. The only exception here is for public APIs, but that's a minority of projects.
- zmmmmm 9y ago> Then I'd change it to a property and recompile You mean, change it to a property, then fix dozens or hundreds of references, possibly in downstream dependencies some of which aren't under your control and can't be changed. Sounds fun.
- alkonaut 9y agoThen that is when you have to change the public field to a property, with no change to calling code. Reasons for going with a property from the start is if you a) ever use reflection (which would need to change depending on whether the storage is a public field vs a property) b) If you need to implement interfaces using the property. Reasons for going with a public field is for special cases where you know a lot about how inlining affects your performance. Typically in structs. Since there is no more boilerplate used to write "public int Id { get; }" vs "public readonly int Id", in 99% of cases I'd choose the latter.