As properties using custom logic (aka any computed property in c#) need a backing field (source one, two), it can occur that you assign to that backing field directly, changing it's value without applying it's setter logic.
You could of course encapsulate this value into some subclass, and then set the accessibility so that this behavior is no longer possible, but I'm looking for a workaround that does not require any further encapsulation, as encapsulating a singular value feels.. silly.
Say I have this class with a value which should always be clamped between 1 and positive infinity, as it may otherwise cause unexpected behavior (some multiplier with a minimum value of 1 for example).
My current workaround is using naming conventions:
public class Foo
{
private float _someVar;
private float b_someMultiplier;
private float _SomeMultiplier
{
get { return b_someMultiplier; }
set { b_someMultiplier = Mathf.Clamp(value, 1, float.PositiveInfinity); }
}
public float SomeVar
{
get { return _someVar; }
}
}
- I prefix my privates with
_
as by the conventions - I name my properties and publics using PascalCase.
- To differentiate between the backing field (which should never be used directly), I mark it with the prefix
b_
.
However, this still makes b_someMultiplier
directly accessible in the Foo
class internally.
Is there some more 'surefire' way of preventing developers to accidentally alter that backing field b_someMultiplier
and skipping the setter logic?
My current way of doing it using naming conventions feels more like a botch than a solution: I'd have to explain this to anyone I send my code to.