What do you mean immutable and mutable? In simple terms, once a immutable object is created, its state will not change. Conversely, if an instance of a class is immutable, then we call this class immutable class.
Advantages of immutable
- Facilitates multithreaded programming
- Conveniently as a key to Hashtable
- Easy to compare status
Note: Changes in itself are called changes, similar to string,int (such as primitive value types) are immutable by default, and if you modify them, just reassign a new one. If it is a custom value type struct, it is best to also specify immutable.
specified by ReadOnly.
Implementation of immutable in C #
The Classic immutable class
ClassContact
{
PublicContact (string fullName, String phonenumber)
{
This. fullName=FullName;
This. PhoneNumber=PhoneNumber;
}
PublicContact ChangeNumber (String newnumber)
{
//Create a new instance
ReturnNewContact (This. FullName, Newnumber);
}
ReadOnlyString FullName;
PublicString FullName{Get{ return Fullname; }}
< Span style= "color: #0000ff;" >readonly string phonenumber;
public uint phonenumber{ get { return phonenumber; }}
}
This example is almost no longer necessary to explain and constructs a new contact object each time changenumber.
C # support for immutability is inseparable from these two keywords: const and readonly. The C # compiler uses these two keywords to ensure that the state of a created object does not change. These two keywords are provided naturally because they are still different. ReadOnly allows changes to its state (initialization) in the constructor, while Const does not. For example:
ClassCnblogs{
Article (StringAuthorStringTitle{
A_title=Title
AuthorName= author; compile here Error
Readonly string a_title;
const string authorname = " freesc}
/span>
(see here for other discussions on ReadOnly and const)
Now you might ask, what if my object references another object through a readonly field? will the state of the referenced object change? The answer is yes, look at the following example:
PublicClassC
{
PrivateStaticReadOnlyInt[] INTs=NewInt[]{ 1, 2, < Span style= "color: #800080;" >3 } public static < Span style= "color: #0000ff;" >int[] ints { get { return ints; }
}
Here if we try to change the value of the array in c: c.ints = null; is an invalid operation, this is a so-called "reference immutable", note here only that the reference is immutable, if you try to use outside of C: c.ints[1] = 123; You will find that the array itself can be changed. We can call the INTs field a "shallow" immutable field. So you can specify the fields you need to immutable with relative flexibility, and you can refer to Eric Lippert's article.
In relation to Hashtable, only the immutable object is the key of the hash to ensure that the hash value is always constant. Of course, the value of a hash is usually calculated from some state (or sub-state) of the object, and the object's states (sub-States) should be immutable.
The following extracts can be used for explanation
In Java strings is immutable. If we have a string and do changes to it, we get new string referenced by the same variable:
String str = "abc";str += "def"; // now str refers to another piece in the heap containing "abcdef" // while "abc" is still somewhere in the heap until taken by GC
It ' s been said that int and double is immutable in C #. Does it mean if we have an int and later change it, we would get new int ' pointed ' by the same variable? Same thing but with stack.
int i = 1;i += 1; // same thing: in the stack there is value 2 to which variable // i is attached, and somewhere in the stack there is value 1
Is that correct? If not, the what's is int immutable?
You haven ' t changed (and cannot change) something about the int; You are assigned a new int value (and discarded the old value). Thus it is immutable.
Consider a more complex struct:
var x = new FooStruct(123);x.Value = 456; // mutatex.SomeMethodThatChangedInternalState(); // mutatex = new FooStruct(456); // **not** a mutate; this is a *reassignment*
However, there is no "pointing" here. The struct is directly on the stack (in this case): no references involved.
On immutable immutability