HOW TO: Initialize shared variables
"Initializing shared variable" is not a HOW TO problem. Here, it is the main one to meet New.
When creating a function function, New is very interesting, Sub New () is different from other functions because it can appear twice.
Public Class TestClass
Shang Sub New ()
'...
End Sub
Sub new ()
'...
End Sub
'...
END CLASS
When Dim T As New TestClass, it executes Shared Sub New () first, then executes Sub New (). Shared Sub New () is only executed, in the instance class, it is performed when the first instance is generated.
Using this feature, Shared Sub New () is particularly convenient to initialize the shared variable of the class.
Let's make a comparison:
In static class,
Public class mycommand 'uses shared subnewely ()
Private shared cn as sqlclient.sqlconnection
Shang Sub New ()
CN = new sqlclient.sqlconnection ("PERSIST Security INFO = FALSE; Integrated Security = SSPI; Database = Northwind; Server = (local)")
End Sub
Public Shared Function Command (Byval CommandText As String) AS Sqlclient.sqlCommand
Return New Sqlclient.sqlcommand (CommandText, CN)
END FUNCTION
END CLASS
Public class mycommand0 'does not use Shared Sub New ()
Private shared cn as sqlclient.sqlconnection
Public Shared Function Command (Byval CommandText As String) AS Sqlclient.sqlCommand
IF cn is nothing then
CN = new sqlclient.sqlconnection ("PERSIST Security INFO = FALSE; Integrated Security = SSPI; Database = Northwind; Server = (local)")
END IF
Return New Sqlclient.sqlcommand (CommandText, CN)
END FUNCTION
END CLASS
In the instance class,
Public class mycommand1 'uses Shared Sub New ()
Private shared cn as sqlclient.sqlconnection
Private_Command as SqlClient.sqlCommand
Shang Sub New ()
CN = new sqlclient.sqlconnection ("PERSIST Security INFO = FALSE; Integrated Security = SSPI; Database = Northwind; Server = (local)")
End Sub
Sub new ()
_Command = New Sqlclient.sqlcommand ("Select * from Orders", CN)
End subsis new (Byval CommandText As String)
_Command = New SqlClient.sqlcommand (CommandText, CN)
End Sub
Public Readonly Property Command () As Sqlclient.sqlCommand
Get
Return _Command
END GET
End Property
'Omitted below ...
END CLASS
Public class mycommand2 'does not use Shared Sub New ()
Private shared cn as sqlclient.sqlconnection
Private_Command as SqlClient.sqlCommand
Sub new ()
IF cn is nothing then
CN = new sqlclient.sqlconnection ("PERSIST Security INFO = FALSE; Integrated Security = SSPI; Database = Northwind; Server = (local)")
END IF
_Command = New Sqlclient.sqlcommand ("Select * from Orders", CN)
End Sub
Sub New (ByVal CommandText As String)
IF cn is nothing then
CN = new sqlclient.sqlconnection ("Ersist security info = false; integrated security = sspi; database = northwind; server = (local)")
END IF
_Command = New SqlClient.sqlcommand (CommandText, CN)
End Sub
Public Readonly Property Command () As Sqlclient.sqlCommand
Get
Return _Command
END GET
End Property
'Omitted below ...
END CLASS