Immutability – Differences Between Immutable Value Types and Reference Types

immutabilitylanguage-agnosticobject-oriented

Value types are types which do not have an identity. When one variable is modified, other instances are not.

Using Javascript syntax as an example, here is how a value type works.

var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is still 42

Reference types are types which do have an identity. When one variable is modified, other instances are as well.

Here is how a reference type works.

var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is now 0

Note how the example uses mutatable objects to show the difference. If the objects were immutable, you couldn't do that, so that kind of testing for value/reference types doesn't work.

Is there any functional difference between immutable value types and immutable reference types? Is there any algorithm that can tell the difference between a reference type and a value type if they are immutable? Reflection is cheating.

I'm wondering this mostly out of curiosity.

Best Answer

You are defining value types and reference in a language agnostic way, but doing so only by example in terms of changing of data members. Logically, making the types immutable makes you lose the only difference guaranteed by your definition (and the answer might be "no").

However, once we start looking at particular programming languages, then yes: there are more differences.

Consider the following C# example.

void increment()
{
    lock (synchro)
    {
        total++;
    }
}

private int total = 0;
private SomeType synchro;

If SomeType is a reference type, this counter will be thread safe. If SomeType is a value type, then, due to boxing, each thread is locking a copy of synchro and increments may be lost under concurrency.

Of course, there are no genuine immutable types in .NET in the most abstract sense, as the monitors involved are implemented using hidden fields (akin to the C++ mutable keyword that can declare mutable members in otherwise immutable types). But on Stack Overflow, everyone will understand your question to refer to anything that their platform calls "immutable".