Reputation: 31
What is the difference between immutable object and immutable variable? are they both unchangeable?
Immutable Variables are variables that cannot change at all. but for simple types is there another name or term for an immutable variable? can we use "read only" or is there a specific term for it?
Upvotes: 2
Views: 3362
Reputation: 152556
What is the difference between immutable object and immutable variable?
An immutable object is an object whose value (meaning its property values) cannot change, either via external accessors or through internal methods.
Does C# have "immutable variables"?
If you consider class members "variables" then Yes. If not, then No. C++ has the concept of "constant" local variables but C# does not.
for simple types is there another name or term for an immutable variable?
Not in the "local variable" sense. In C# there are two types of class members that cannot change. One is readonly
, which can be set at run-time as part of object construction (or static construction for a static redaonly
field).
The other is constant
, which is similar to readonly
, but the value of the constant is baked into the binary code of the class, meaning that any time the field is referenced the value is substituted into the compiled code.
Upvotes: 4
Reputation: 4826
An immutable object is one that cannot be changed (with the expectation that you get the same object back). This might be slightly confusing, so let me explain one of the simplest examples I can think of. Say I have the following code:
string myString = "Hello World!";
Strings are an example of immutable objects. Now, obviously you can change the value of myString
, however, you are not simply making changes to the myString
object when you do this. The language actually creates a NEW string object that myString
will point to. (I cannot remember the exact details for how this works, for the reason why, see this answer)
//This is creating a new string object, although it looks like a simple
//manipulation of what currently exists.
myString = "Goodbye World!";
Immutable variables (as you call them) on the other hand (commonly referred to as "constants" or "constant fields" in my experience), CANNOT change. Your compiler will complain if you attempt to modify it in any way. There are many reasons why you'd want to do that (a Google search will give you dozens). In short, make a field constant where you know the value will never and should never be altered, even if by accident.
This might be a weak example, but say you have a program that builds a Vehicle
object and you know the most wheels you will ever need is 18. You could say:
const int MAX_WHEELS = 18;
And that can never change by accident. Any time you use MAX_WHEELS, it will always be 18. I do not know the details, but it seems likely that the compiler will just substitute value in for the field name, but maybe someone can correct me on that.
Upvotes: 1