Search code examples
vb.netoption-strict

Dealing with error message narrowing from type object to type string


I am getting this error message when converting code from .Net 2.0 to .Net 4.5:

Option strict on disallows narrowing from type 'object' to type 'string' in copying the value of 'ByRef' parameter 'ParamValue' back to the matching argument.

The code looks like this:

Public Shared Function TheFunction(ByRef x As Object ) As Integer
    TheFunction = 5
    // ultimately called like this: SqlCommand.Parameters.AddWithValue("field", x)
End Function

Private Function AFunction(ByVal x As String) As Boolean

   Dim cnt As Integer = TheFunction(x)

End Function

I have googled for answers and it seems the suggestion is to change the TheFunction.

I am constrained in that I cannot change TheFunction.

I can turn off strict, but I would rather put in a good fix for this problem like copying x to a different variable and passing that variable in.


Solution

  • Would this work?

    Dim boxedObject as Object = CType(x, Object)
    Dim cnt As Integer = TheFunction(boxedObject)
    x = CType(boxedObject, String)