Pouya Samie
Pouya Samie

Reputation: 3723

VBCodeProvider Can not cast correctly the Implicit Variable declaration on compile

I am Compiling My string Code(I read My Code from Text File) In vb and it works fine but i have a function that returns nullable double(Double?)

when i use it like this

Dim x As Double? = Myfunc(1000) 'it returns Nothing

my x variable fills with Nothing and it's ok

But When I use it like this

Dim x = Myfunc(1000) 'it returns Nothing

my x value is 0 !!!!

How can i solve this problem i want my users write codes like first code block

i tested all Option Explicit and Option Strict but it did not gain me anything.

please let me know how can i use Just dim x not Dim x as (type) thank you for your helps

UPDATE :this is Myfunc Code :

   Function Myfunc(parameterId As Long) As Double?

        If parameterId = 1000 Then
               Return Nothing
        Else
            Return tot(parameterId) 'it is a dictionary of values
        End If

    End Function

And this Is my Compile Class :

     Private Shared Function Compile(ByVal vbCode As String) As CompilerResults
        Dim providerOptions = New Dictionary(Of String, String)
        providerOptions.Add("CompilerVersion", "v4.0")

        ' Create the VB.NET compiler.
        Dim vbProv = New VBCodeProvider(providerOptions)
        ' Create parameters to pass to the compiler.
        Dim vbParams = New CompilerParameters()
        ' Add referenced assemblies.



        vbParams.ReferencedAssemblies.Add("mscorlib.dll")
        vbParams.ReferencedAssemblies.Add("System.Core.dll")
        vbParams.ReferencedAssemblies.Add("System.dll")
        vbParams.ReferencedAssemblies.Add("System.Windows.Forms.dll")
        vbParams.ReferencedAssemblies.Add("System.Data.dll")
        vbParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
        vbParams.ReferencedAssemblies.Add("System.Xml.dll")
        vbParams.ReferencedAssemblies.Add("System.Xml.Linq.dll")


        vbParams.GenerateExecutable = False
        ' Ensure we generate an assembly in memory and not as a physical file.
        vbParams.GenerateInMemory = True

        ' Compile the code and get the compiler results (contains errors, etc.)
        Return vbProv.CompileAssemblyFromSource(vbParams, vbCode)

    End Function

Upvotes: 0

Views: 300

Answers (1)

Grim
Grim

Reputation: 672

As discussed above, Option Infer On needs to be included to force the compiler to create the variable as the required type - in this case the Double? returned by MyFunc.

Upvotes: 2

Related Questions