❔ Are there standards to whether someone should use fields or properties?
I always spend a second thinking if I should use fields or properties when I am making classes. I'm not sure which one to use ever aside from having a public getter and private setter but it always works out anyways lol. Is there a standard that I can follow in order to properly use fields and properties?
I also have a question about using reference types in structs. I have read in most places that it is generally frowned upon to use reference type inside of structures, but I have also seen and read many things that do this. What is the general consensus on using reference types inside of structures, or when is it OK to do this?
4 Replies
fields for private members, properties for public members
Property should represent exposed functionality of your class.
While fields are internal data layout that is implementation detail, something outside of that class doesn't need to know about
the general expectations from the API design standpoint is that value types can be perfectly copied by reassigning them. if you have a mutable list in a value type, it is no longer actually deeply copied if you reassign it, but it's fine as long as you're careful and explicit about it. value types holding reference types is fine as long as those objects aren't mutable, or it's explicit that they are. so references to immutable objects are completely fine
in general, structs usually shouldn't have mutating members, like non-readonly getters, or non-readonly methods, because they can cause unexpected copies if you're not careful. but if you're careful or using an analyzer that detects these, it's fine
if you're confident in your competence, you can do whatever, as long as you make it clear to others and it makes sense
fields can be passed by ref, that's their only benefit. properties might be necessary if you're implementing interfaces with these properties. I'd argue you should use public fields for large structs, because it's convenient to pass things by ref that way. for classes, the general consensus is to use properties whenever possible. if you want a property to be readonly btw, you can simulate it via a get-only property
the benefit of properties is that they are more comfy for API consumers, and that you can change the implementation without affecting the interface, but that's only relevant for libraries basically
ah yes, forgot to mention that many frameworks, e.g. the json serialization frameworks, ignore fields by default, only looking at properties for serialization, so keep that in mind too. you can work around it in some cases, but it might not be worth the trouble
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.