Is there any difference between declaring and constructing an object of type value?

I have been working in .NET for a while, but sometimes I am still confused by the inconsistencies between the framework and my previous experience with C ++.

In .NET, all objects are either value types or reference types. Link types are allocated on the heap, while value types are allocated on the stack (in the current CLR implementation, anyway). I understand. However, at least in VB.NET you can still define a constructor for a value type. You can do it:

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

Dim c As Coordinates, c Dim c As New Coordinates(10, 20, 30). ? , new , . , - , .

: new , :

Dim c1 As Coordinates
Dim c2 As New Coordinates

- ?


EDIT: , . :

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 '

, , , ; . , :

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 '
+3
3

New :

Dim c2 As New Coordinates

:

Dim c2 As Coordinates = New Coordinates()

, , (.. ), :

Public Sub New()
   x = 0
   y = 0
   z = 0
End Sub

VB , c1, New, . , :

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

:

c1.x = 1, c2.x = 1
c1.x = 2, c2.x = 1
c1.x = 3, c2.x = 1

c1 , c2 , .

, . , , , :

Public Shared Function Create(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As Coordinates
   Dim item As Coordinates
   item.x = x
   item.y = y
   item.z = z
   Return item
End Function

Dim c3 As Coordinates = Coordinates.Create(1, 2, 3)
+3

( ) ( , ).

VB.Net(EDIT)

;), .

#:

Coordinates c1; Coordinates c2 = New Coordinates(); , 1- , . struct.

, .

+2

VB.Net,

Dim c1 As Coordinates
Dim c2 As New Coordinates

. # c1.X (), c2.X 0.

VB , 0 ( 0.0 false ...), # .

, :

 Sub New()
    Me.x = 1
    Me.y = 2
    Me.z = 3
 End Sub

"".

+1

Source: https://habr.com/ru/post/1719114/


All Articles