I was trying to consolidate a bunch of repeat code into a utility class with the following structure:
public class Shared<T>
{
private volatile T _value;
public object Lock { get; private set; }
public T Value
{
get { lock (Lock) return _value; }
set { lock (Lock) _value = value; }
}
public Shared(T startingValue)
{
_value = startingValue;
Lock = new object();
}
public Shared()
: this(default(T))
{
}
}
However, C# will not let me. The documentation indicates that T
must be a reference type or one of the primitives (int, bool, etc.). The only types I care about are reference types and bools. Obviously, I cannot use an unbounded type T
. Is there a way I can make this work? Is it even possible to add constraints to this to make it work as a Shared<bool>
? I'm not even allowed to mark other struct types volatile. :(
If there is no possible way to mark it volatile, do I have other assurances that it will not be optimized away when multiple threads are trying to read this value?