I've been working in .NET for some time now, but occasionally I still get confused by a disparity between the framework and my prior experience in C++.
In .NET, all objects are either value types or reference types. Reference types are allocated on the heap while value types are allocated on the stack (in the current CLR implementation, anyway). I get that. However, at least in VB.NET, you can still define a constructor on a value type. You can do this:
Public Structure Coordinates
Public x As Integer
Public y As Integer
Public z As Integer
Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
Me.x = x
Me.y = y
Me.z = z
End Sub
End Structure
With this code in place, I can write Dim c As Coordinates
and then access the members of c
myself, or I can write Dim c As New Coordinates(10, 20, 30)
. What is the difference between these two approaches? Obviously the new
keyword is not allocating the object on the heap since it's a value type. I'm just not clear on whether constructors on value types are merely a convenience or if they actually do something other than execute like any other method.
To perhaps make my point clearer: I could easily have removed the definition for New
in the above code, and still I could do this:
Dim c1 As Coordinates
Dim c2 As New Coordinates
Do these two lines do anything different?
EDIT: Guffa has pointed out that declaring and constructing are not the same. The following code demonstrates this:
For i As Integer = 1 To 3
Dim c1 As Coordinates
Dim c2 As New Coordinates
c1.x += 1
c2.x += 1
Console.WriteLine("c1.x = {0}, c2.x = {1}", c1.x, c2.x)
Next
' output: '
' c1.x = 1, c2.x = 1 '
' c1.x = 2, c2.x = 1 '
' c1.x = 3, c2.x = 1 '
So, in a scenario involving iteration, local variables representing value types are not re-allocated on the stack; they stay put. I took a look at this same scenario using plain old integers and found the same behavior:
For i As Integer = 1 To 3
Dim x As Integer
Dim y As New Integer
x += 1
y += 1
Console.WriteLine("x = {0}, y = {1}", x, y)
Next
' output: '
' x = 1, y = 1 '
' x = 2, y = 1 '
' x = 3, y = 1 '