How to freeze a popsicle in .NET (make a class immutable)

Maybe slightly off topic but just out of curiosity :) Why don't you use "real" immutability? e.g. making Freeze() return an immutable copy (without "write methods" or any other possibility to change the inner state) and using this copy instead of the original object. You could even go without changing the state and return a new copy (with the changed state) on each write operation instead (afaik the string class works this). "Real immutability" is inherently thread safe.


I vote for Attempt 5, use the lock(this) implementation.

This is the most reliable means of making this work. Reader/writer locks could be employed, but to very little gain. Just go with using a normal lock.

If necessary you could improve the 'frozen' performance by first checking _isFrozen and then locking:

void Freeze() { lock (this) _isFrozen = true; }
object ReadValue()
{
    if (_isFrozen)
        return Read();
    else
        lock (this) return Read();
}
void WriteValue(object value)
{
    lock (this)
    {
        if (_isFrozen) throw new InvalidOperationException();
        Write(value);
    }
}