Nick Randell Nick Randell - 9 months ago 47
C# Question

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

I'm looking for a way to allow a property in a C# object to be set once only. It's easy to write the code to do this, but I would rather use a standard mechanism if one exists.

public OneShot<int> SetOnceProperty { get; set; }

What I want to happen is that the property can be set if it is not already set, but throw an exception if it has been set before. It should function like a Nullable value where I can check to see if it has been set or not.

Answer Source

There is direct support for this in the TPL in .NET 4.0; 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
            if (!hasValue) throw new InvalidOperationException("Value not set");
            return value;
            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; } }