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

C#.Net

C# Problem Overview


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.

C# Solutions


Solution 1 - 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; } }

Solution 2 - C#

You can roll your own (see the end of the answer for a more robust implementation that is thread safe and supports default values).

public class SetOnce<T>
{
    private bool set;
    private T value;

    public T Value
    {
        get { return value; }
        set
        {
            if (set) throw new AlreadySetException(value);
            set = true;
            this.value = value;
        }
    }

    public static implicit operator T(SetOnce<T> toConvert)
    {
        return toConvert.value;
    }
}

You can use it like so:

public class Foo
{
    private readonly SetOnce<int> toBeSetOnce = new SetOnce<int>();

    public int ToBeSetOnce
    {
        get { return toBeSetOnce; }
        set { toBeSetOnce.Value = value; }
    }
}

More robust implementation below

public class SetOnce<T>
{
    private readonly object syncLock = new object();
    private readonly bool throwIfNotSet;
    private readonly string valueName;
    private bool set;
    private T value;

    public SetOnce(string valueName)
    {
        this.valueName = valueName;
        throwIfGet = true;
    }

    public SetOnce(string valueName, T defaultValue)
    {
        this.valueName = valueName;
        value = defaultValue;
    }

    public T Value
    {
        get
        {
            lock (syncLock)
            {
                if (!set && throwIfNotSet) throw new ValueNotSetException(valueName);
                return value;
            }
        }
        set
        {
            lock (syncLock)
            {
                if (set) throw new AlreadySetException(valueName, value);
                set = true;
                this.value = value;
            }
        }
    }

    public static implicit operator T(SetOnce<T> toConvert)
    {
        return toConvert.value;
    }
}


public class NamedValueException : InvalidOperationException
{
    private readonly string valueName;

    public NamedValueException(string valueName, string messageFormat)
        : base(string.Format(messageFormat, valueName))
    {
        this.valueName = valueName;
    }

    public string ValueName
    {
        get { return valueName; }
    }
}

public class AlreadySetException : NamedValueException
{
    private const string MESSAGE = "The value \"{0}\" has already been set.";

    public AlreadySetException(string valueName)
        : base(valueName, MESSAGE)
    {
    }
}

public class ValueNotSetException : NamedValueException
{
    private const string MESSAGE = "The value \"{0}\" has not yet been set.";

    public ValueNotSetException(string valueName)
        : base(valueName, MESSAGE)
    {
    }
}

Solution 3 - C#

This can be done with either fiddling with flag:

private OneShot<int> setOnce;
private bool setOnceSet;

public OneShot<int> SetOnce
{
    get { return setOnce; }
    set
    {
        if(setOnceSet)
            throw new InvalidOperationException();
            
        setOnce = value;
        setOnceSet = true;
    }
}

which is not good since you can potentially receive a run-time error. It's much better to enforce this behavior at compile-time:

public class Foo
{
    private readonly OneShot<int> setOnce;        
    
    public OneShot<int> SetOnce
    {
        get { return setOnce; }
    }
    
    public Foo() :
        this(null)
    {
    }
    
    public Foo(OneShot<int> setOnce)
    {
        this.setOnce = setOnce;
    }
}

and then use either constructor.

Solution 4 - C#

C# 9 has this feature build in. It is called Init only setters

public DateTime RecordedAt { get; init; }

Solution 5 - C#

No such feature in C# (as of 3.5). You have to code it yourself.

Solution 6 - C#

As Marc said there is no way to do this by default in .Net but adding one yourself is not too difficult.

public class SetOnceValue<T> { 
  private T m_value;
  private bool m_isSet;
  public bool IsSet { get { return m_isSet; }}
  public T Value { get {
    if ( !IsSet ) {
       throw new InvalidOperationException("Value not set");
    }
    return m_value;
  }
  public T ValueOrDefault { get { return m_isSet ? m_value : default(T); }}
  public SetOnceValue() { }
  public void SetValue(T value) {
    if ( IsSet ) {
      throw new InvalidOperationException("Already set");
    }
    m_value = value;
    m_isSet = true;
  }
}

You can then use this as the backing for your particular property.

Solution 7 - C#

Have you considered readonly? http://en.csharp-online.net/const,_static_and_readonly

It's only available to set during init, but might be what you are looking for.

Solution 8 - C#

Here's my take on this:

public class ReadOnly<T> // or WriteOnce<T> or whatever name floats your boat
{
	private readonly TaskCompletionSource<T> _tcs = new TaskCompletionSource<T>();

	public Task<T> ValueAsync => _tcs.Task;
	public T Value => _tcs.Task.Result;

	public bool TrySetInitialValue(T value)
	{
		try
		{
			_tcs.SetResult(value);
			return true;
		}
		catch (InvalidOperationException)
		{
			return false;
		}
	}

	public void SetInitialValue(T value)
	{
		if (!TrySetInitialValue(value))
			throw new InvalidOperationException("The value has already been set.");
	}

	public static implicit operator T(ReadOnly<T> readOnly) => readOnly.Value;
	public static implicit operator Task<T>(ReadOnly<T> readOnly) => readOnly.ValueAsync;
}

Marc's answer suggests the TPL provides this functionality and I think TaskCompletionSource<T> might have been what he meant, but I can't be sure.

Some nice properties of my solution:

  • TaskCompletionSource<T> is an officially support MS class which simplifies the implementation.

  • You can choose to synchronously or asynchronously get the value.

  • An instance of this class will implicitly convert to the type of value it stores. This can tidy up your code a little bit when you need to pass the value around.

Solution 9 - C#

/// <summary>
/// Wrapper for once inizialization
/// </summary>
public class WriteOnce<T>
{
    private T _value;
    private Int32 _hasValue;

    public T Value
    {
        get { return _value; }
        set
        {
            if (Interlocked.CompareExchange(ref _hasValue, 1, 0) == 0)
                _value = value;
            else
                throw new Exception(String.Format("You can't inizialize class instance {0} twice", typeof(WriteOnce<T>)));
        }
    }

    public WriteOnce(T defaultValue)
    {
        _value = defaultValue;
    }

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

Solution 10 - C#

interface IFoo {

    int Bar { get; }
}

class Foo : IFoo {

    public int Bar { get; set; }
}

class Program {

    public static void Main() {
        
        IFoo myFoo = new Foo() {
            Bar = 5 // valid
        };

        int five = myFoo.Bar; // valid

        myFoo.Bar = 6; // compilation error
    }
}

Notice that myFoo is declared as an IFoo, but instantiated as a Foo.

This means that Bar can be set within the initializer block, but not through a later reference to myFoo.

Solution 11 - C#

The answers assume that objects that receive a reference to an object in the future will not try to change it. If you want to protect against this, you need to make your write-once code only work for types that implement ICloneable or are primitives. the String type implements ICloneable for example. then you would return a clone of the data or new instance of the primitive instead of the actual data.

Generics for primitives only: T GetObject where T: struct;

This is not needed if you know that objects that get a reference to the data will never overwrite it.

Also, consider if the ReadOnlyCollection will work for your application. an exception is thrown whenever a change is attempted on the data.

Solution 12 - C#

While the accepted and top-rated answers most directly answer this (older) question, another strategy would be to build a class hierarchy such that you can construct children via parents, plus the new properties:

public class CreatedAtPointA 
{
    public int ExamplePropOne { get; }
    public bool ExamplePropTwo { get; }

    public CreatedAtPointA(int examplePropOne, bool examplePropTwo)
    {
        ExamplePropOne = examplePropOne;
        ExamplePropTwo = examplePropTwo;
    }
}

public class CreatedAtPointB : CreatedAtPointA
{
    public string ExamplePropThree { get; }

    public CreatedAtPointB(CreatedAtPointA dataFromPointA, string examplePropThree) 
        : base(dataFromPointA.ExamplePropOne, dataFromPointA.ExamplePropTwo)
    {
        ExamplePropThree = examplePropThree;
    }
}

By relying on constructors, you can spray some Febreeze on the code smell, though it's still tedious and a potentially expensive strategy.

Solution 13 - C#

I created a type which allows a value to be set on construction, then after that the value can only be set/overridden once, otherwise an exception is thrown.

public class SetOnce<T>
{
    bool set;
    T value;
    
    public SetOnce(T init) =>
        this.value = init;
        
    public T Value
    {
        get => this.value;
        set
        {
            if (this.set) throw new AlreadySetException($"Not permitted to override {this.Value}.");
            this.set = true;
            this.value = value;
        }
    }

    public static implicit operator T(SetOnce<T> setOnce) =>
        setOnce.value;

    class AlreadySetException : Exception
    {
        public AlreadySetException(string message) : base(message){}
    }
}

Solution 14 - C#

You can do this but is not a clear solution and code readability is not the best. If you are doing code design you can have a look at singleton realization in tandem with AOP to intercept setters. The realization is just 123 :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick RandellView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#Michael MeadowsView Answer on Stackoverflow
Solution 3 - C#Anton GogolevView Answer on Stackoverflow
Solution 4 - C#Tono NamView Answer on Stackoverflow
Solution 5 - C#VizuView Answer on Stackoverflow
Solution 6 - C#JaredParView Answer on Stackoverflow
Solution 7 - C#Josh WinklerView Answer on Stackoverflow
Solution 8 - C#Ronnie OverbyView Answer on Stackoverflow
Solution 9 - C#Smagin AlexeyView Answer on Stackoverflow
Solution 10 - C#allonhadayaView Answer on Stackoverflow
Solution 11 - C#VoteCoffeeView Answer on Stackoverflow
Solution 12 - C#StarFoxView Answer on Stackoverflow
Solution 13 - C#PelletView Answer on Stackoverflow
Solution 14 - C#ruslanderView Answer on Stackoverflow