In the below code I am not understanding the role played by ReadOnly. I elaborate my question below:
Structure Mutable
Private x As Integer
Public Function Mutate() As Integer
x = x + 1
Return x
End Function
End Structure
Module Module1
Public ReadOnly m As Mutable 'Statement 1
Sub Main()
Console.WriteLine(m.Mutate()) ' 1 Statement 2
Console.WriteLine(m.Mutate()) ' 1
Console.WriteLine(m.Mutate()) ' 1
Console.ReadLine()
End Sub
End Module
How the control behaves if the ReadOnly keyword was not there:
- Statement 1 would read as: Public m As Mutable
- Upon execution of statement 1, an instance “m” gets created in the stack memory which is large enough to fit an integer type value “x” in it. The default value of x is 0
- m.Mutate() gets executed the first time. The control calls the function Mutate() where x = x+1 gets executed which increases the value of x by 1
- The value of x = 1 is returned to the function Mutate() which is then displayed.
- Steps 3 and 4 get repeated for the next two times when Mutate() function is called. The key point is that the value of x increases from 0 to 1, then from 1 to 2 and then finally to 3.
What is the difference when we add the ReadOnly keyword?
- m.mutate() gets executed the first time which increases the value of x from 0 to 1. This is returned and “1” gets printed
- But when the control shifts to the next line i.e. statement 2,and after the Mutate() function is called again I see from a break-point analysis that it is then the value of x is reset to 0 from 1. The function Mutate gets executed which increases the value again from 0 to 1 which gets printed. This is the main difference.
My Question: Why does the presence of ReadOnly keyword reset the value of x to 0 everytime the function Mutate is called? In this case, “m” is a local variable storing an instance of the structure. When an instance of a structure is declared as ReadOnly in VB.Net what is the implication? In such cases, should I understand the role of ReadOnly as “write once and reset if called again”? Can someone please explain the point.
My confusion stems from the fact that ReadOnly in VB.Net can be only used on Properties and Member Variables (Fields). When that is the case, their values can be set in the constructor of that structure/class or at declaration. But here “m” stores an instance. So what changes are being introduced when ReadOnly is being used on an instance?
In short how should I understand why using the ReadOnly keyword gives the output as “1 1 1”?