Think of it in terms of semantics. An object has certain properties that are immediately obvious and available: color, height, width and so on.
Properties in C# are for such values that are immediately available or at least extremely cheap to retrieve or form. Seeing a property tells me that getting the value is a very small op and has no side effects.
A method on the other hand is like asking/telling the object to do something that can take a bit of time and resources to do.
So if the value you are trying to read is expensive to get and isn't immediately available then the method approach works and as a developer I'll avoid making multiple calls to it unless absolutely necessary because the method is also a possible indication that it might change state.
That’s a good argument. I had not considered properties in those terms before, and have historically been skeptical of them in many languages.
I’m partly convinced now! I still worry a bit about property authors who don’t follow the “cheap, non-side-effectful, externally cacheable” rules, though. Perhaps there are linters in property-ful languages which would help with that.
> I still worry a bit about property authors who don’t follow the “cheap, non-side-effectful, externally cacheable” rules, though. Perhaps there are linters in property-ful languages which would help with that.
Definitely a problem when a developer goes rogue and breaks this rule. I'm not sure if there are linters that helper with this. I don't think either VS, Rider, or the .NET Compiler include any analyzers that complain about this. If they do, I haven't seen the warnings before. I generally tend to enforce this during code reviews with my team.
Properties in C# are for such values that are immediately available or at least extremely cheap to retrieve or form. Seeing a property tells me that getting the value is a very small op and has no side effects.
A method on the other hand is like asking/telling the object to do something that can take a bit of time and resources to do.
So if the value you are trying to read is expensive to get and isn't immediately available then the method approach works and as a developer I'll avoid making multiple calls to it unless absolutely necessary because the method is also a possible indication that it might change state.