Immutable object pattern in C# – what do you think? [closed]

For info, the second approach is called “popsicle immutability”.

Eric Lippert has a series of blog entries on immutability starting here. I’m still getting to grips with the CTP (C# 4.0), but it looks interesting what optional / named parameters (to the .ctor) might do here (when mapped to readonly fields)…
[update: I’ve blogged on this here]

For info, I probably wouldn’t make those methods virtual – we probably don’t want subclasses being able to make it non-freezable. If you want them to be able to add extra code, I’d suggest something like:

[public|protected] void Freeze()
{
    if(!frozen)
    {
        frozen = true;
        OnFrozen();
    }
}
protected virtual void OnFrozen() {} // subclass can add code here.

Also – AOP (such as PostSharp) might be a viable option for adding all those ThrowIfFrozen() checks.

(apologies if I have changed terminology / method names – SO doesn’t keep the original post visible when composing replies)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)