Search code examples
asp.netvb.netclass

Difference in Initiating a Class


What is the difference between these two methods of initiating a new class? Both work, but I'm wondering what and why the technical difference is.

Version 1 of initiating the class.

Dim sMyClassVersion1 As New Class1()

Version 2 of initiating the class.

Dim sMyClassVersion2 As Class1 = New Class1()

Shown in a code example:

Public Class Class1
    Private MyValue As Integer

    Public Sub New()
        MyValue = 4
    End Sub

    Public Function MyFunction() As Integer
        Return MyValue * 100
    End Function
End Class

Partial Class MyWebPage
    Inherits System.Web.UI.Page

'Version 1 of initiating the class.
    Dim sMyClassVersion1 As New Class1()

'Version 2 of initiating the class.
    Dim sMyClassVersion2 As Class1 = New Class1()

    Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Response.Write(sMyClassVersion1.MyFunction())
    End Sub
End Class

Solution

  • The best way to know is to use an online tool, like sharplab.io, to see the generated code.

    At the end of the day, both ways to initialize the instance produce the same code.

    IL_0006: ldarg.0
    IL_0007: newobj instance void Class1::.ctor()
    IL_000c: stfld class Class1 MyWebPage::sMyClassVersion1
    
    IL_0011: ldarg.0
    IL_0012: newobj instance void Class1::.ctor()
    IL_0017: stfld class Class1 MyWebPage::sMyClassVersion2