DEV Community

Discussion on: Read-once variable - R1V, ROV, ... - in C#

Collapse
 
upperavenue profile image
Jamie • Edited

A little late to the party, but here's my implementation using implicit conversion to and from the ReadLimit class.

class ReadLimit<T>
{
    private T _value;
    private readonly T _default;
    private int _maxReads;

    public ReadLimit(T value, int maxReads = 1, T defaultValue = default(T))
    {
        _value = value;
        _default = defaultValue;
        _maxReads = maxReads;
    }

    public int Reads { get; private set; }

    public T Value => Reads++ == _maxReads ? (_value = _default) : _value;

    public override string ToString() => Value?.ToString();

    public static implicit operator T(ReadLimit<T> limit) => limit.Value;

    public static implicit operator ReadLimit<T>(T value) => new ReadLimit<T>(value);
}