I have a class that has some properties. And I want something that calculates a Score out of these properties. Since this is a trivial task (some additions and divisions, but nothing spectacular).
So naturally, the question is: ‘When to use a Property with some code in the getter, and when to use a function?’, and that question was already answered.
Now, I wonder about one thing though: If – against all expectations – I ever needed to make this Getter so complicated that it should be a function (for example, because I need to put data in or because it can throw an exception or whatever), is it easy to change a Property into a Method?
Of course, it seems really trivial, just changing
public double Score { get { return Math.Round(A + B / C * D,3); } }
to
public double Score(){ return Math.Round(A + B / C * D,3); }
But I wonder: Are there any side effects? Is anything going to break when changing stuff around like this? I can only ever see this as a possible problem when Reflection is involved, but what in situations where I have 2 Assemblies – one that defines the class and one that uses the class – and only change the one that contains the class without recompiling the consumer assembly. Is that a possible source of ‘weird bugs that are nearly impossible to track’ or is it completely safe to change Properties to Methods?
No. There are no side affects to this at all.
Under the hood the
getandsetaccessors in a property are simply converted toget_MyPropertyName()andset_MyPropertyName()methods. This is also why you can (but typically shouldn’t) add parameters to a property.The only ‘gotcha’ is that in C# you will need to add ‘()’ to any existing calls.
Also