As others have said what you've posted isn't immutable. This is what an immutable object looks like. The readonly
keyword means that the only place that the backing field for the property can be set is in the constructor. Essentially, after the object is constructed that's it forever.
public class ImmutableSomething
{
private readonly int _someInt;
public int SomeInt
{
get
{
return _someInt;
}
}
public ImmutableSomething(int i)
{
_someInt = i;
}
public Add(int i){
return new ImmutableSomething(_someInt + i);
}
}
This is a big deal in functional programming because instead of talking about objects you get to talk about Values. Values never change, so you know that when you pass them to a function or method your original value will never be changed or updated. With mutable objects you can't make that guarantee.
Code built with immutable objects can be easily parallelized because there is no writable shared state. If some other thread gets your Value and wants to do something to it, it can't. "Changing" it in any way produces a new object with a brand new spot in memory just for that object.
So once you're dealing with values you can do some special things like interning which is what .NET does with strings. Because "Hello World" is a value and will never change, one reference to "Hello World" is just as good as any other, so instead of having "Hello World" in a hundred slots in memory, you have it in one slot and set all the references to "Hello World" to point to that one slot. So you get a big win on the memory side but you pay a performance penalty because whenever you create a new string you have to check the intern pool to make sure it doesn't already exist.