Is there a way of setting a property once only in C#

There is direct support for this in the TPL in .NET 4.0;

(edit: the above sentence was written in anticipation of System.Threading.WriteOnce<T> which existed in the “preview” bits available at the time, but this seems to have evaporated before the TPL hit RTM/GA)

until then just do the check yourself… it isn’t many lines, from what I recall…

something like:

public sealed class WriteOnce<T>
{
    private T value;
    private bool hasValue;
    public override string ToString()
    {
        return hasValue ? Convert.ToString(value) : "";
    }
    public T Value
    {
        get
        {
            if (!hasValue) throw new InvalidOperationException("Value not set");
            return value;
        }
        set
        {
            if (hasValue) throw new InvalidOperationException("Value already set");
            this.value = value;
            this.hasValue = true;
        }
    }
    public T ValueOrDefault { get { return value; } }

    public static implicit operator T(WriteOnce<T> value) { return value.Value; }
}

Then use, for example:

readonly WriteOnce<string> name = new WriteOnce<string>();
public WriteOnce<string> Name { get { return name; } }

Leave a Comment