Switching Byref in Byval to VB.NET method calls

Switching Byref to Byval on method calls

I have many warnings caused by:

"Implicit conversion from xxxx to yyyy when copying the value of the ByRef zzzz parameter back to the corresponding argument."

I feel it would be safe to change function parameters from byref to byval, since nothing is done with reference type pointers inside these methods, reference types are just used, and I think that the behavior will be just like that when starting with a copy pointer, not original.

Another consideration is that I have two classes that inherit from the base class. The same situation occurs when the byref parameters cause implicit casting from the base class to a narrower concrete class. Again, I do not see any problems with this running byte of code.

Does anyone have any advice on using parameters in functions when working with reference types?

Some of the other things currently being passed byref in my project are database connection objects, i.e. OracleConnection and SqlConnection. Is there any good reason to pass them around byref?

Example 1

Implicit conversion from "Object" to "Integer" when copying the value of the parameter "ByRef" "value" back to the corresponding argument.

Call Code:

cmd = New SqlCommand()

cmd.Parameters.Add(CreateParameter("Alpha", SqlDbType.Int,ParameterDirection.Input, -1, AlphaValue))

Functions:

Private Function CreateParameter(ByVal parameterName As String, ByVal dbType As SqlDbType, ByVal direction As ParameterDirection, ByVal size As Integer, ByRef value As Object) As SqlParameter
    Dim retParam As SqlParameter
    retParam = New SqlParameter(parameterName, dbType)
    retParam.Direction = direction
    retParam.Size = size
    retParam.Value = value
    Return retParam
End Function

Example 2

"System.Data.IDataReader" "System.Data.SqlClient.SqlDataReader" "ByRef" "reader" .

:

Dim reader As new SqlDataReader

ReleaseReader(reader)

:

    Public Sub ReleaseReader(ByRef reader As IDataReader)
        If reader IsNot Nothing Then
            If Not reader.IsClosed Then
                reader.Close()
            End If
            reader.Dispose()
        End If
    End Sub
+3
1

VB.Net #, , (ByVal), ByRef. , ByVal.

, , , ByVal , ByRef. , .

:

Public Sub ExampleMethod(ByRef p1 As Object) 
  p1 = "foo"
End Sub

Public Sub ExampleMethodWrapper(ByVal p1 as Object)
  ExampleMethod(p1)
End Sub 

Public Sub Test()
  Dim v1 As String = "hello"
  Dim v2 As String = "world" 
  ExampleMethod(v1) ' Warning generated
  ExampleMethodWrapper(v2) ' No warning
End Sub
+5

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


All Articles