Why are ints and doubles immutable? What is the purpose of returning a new object each time you want to change the value?
The reason I ask is because I’m making a class: BoundedInt, which has a value and an upper and lower bound. So I was wondering: should I make this type immutable too? (Or should it be a struct?)
Firstly:
I think you might be mistaken about how value types work. This isn’t some costly operation like you may be imagining; it’s simply the overwriting of data (as opposed to, e.g., dynamic allocation of new memory).
Secondly: here’s a very simple example of why numbers are immutable:
Granted, that is a contrived example. So let’s consider a couple more involved ideas.
Mutable reference type
First, there’s this one: what if
Integerwere a mutable reference type?Then we could have code like this:
And:
This seems to defy intuition: that the line
t2.Integer = t1.Integerwould simply copy a value (actually, it does; but that “value” is in fact a reference) and thus thatt2.Integerwould remain independent oft1.Integer.Mutable value type
This could be approached another way, of course, keeping
Integeras a value type but maintaining its mutability:But now let’s say we do this:
Basically, immutability of values is something that is highly intuitive. The opposite is highly unintuitive.
I guess that is subjective, though, in all fairness 😉