'TestString' is not declared. It may be inaccessible due to its protection level. (BC30451)

22.4k views Asked by At

I am trying out some on the fly code compilation using the VBCodeProvider class. What I want to be able to do is modify a public variable in my assembly in the code.

I have a Public TestString As String = "" in my application.

This is the code I am using to compile:

    Dim codeProvider As New VBCodeProvider()
    Dim optParams As New CompilerParameters
    optParams.ReferencedAssemblies.Add("MyAssembly.exe")
    optParams.ReferencedAssemblies.Add("system.windows.forms.dll")
    optParams.CompilerOptions = "/t:library"
    optParams.GenerateInMemory = True
    Dim results As CompilerResults = codeProvider.CompileAssemblyFromSource(optParams, RichTextBox1.Text)

    If results.Errors.Count > 0 Then
        Dim sb As New StringBuilder("Compilation Failed with the following error(s)" + CR_LF + CR_LF)
        For Each CompErr As CompilerError In results.Errors
            sb.Append(String.Format("Line {0} - {1} ({2}){3}", CompErr.Line, CompErr.ErrorText, CompErr.ErrorNumber, CR_LF))
        Next
        MessageBox.Show(sb.ToString, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        Dim assy As System.Reflection.Assembly = results.CompiledAssembly
        Dim exeinstance As Object = assy.CreateInstance("Script")
        Dim typ As Type = exeinstance.GetType
        Dim method As MethodInfo = typ.GetMethod("Main")
        method.Invoke(exeinstance, Nothing)
    End If

This is the code in my textbox:

Imports System
Imports MyAssembly

Class Script
    Sub Main()
       TestString="foo"' <-- This line fails compilation
    End Sub
End Class

The error I get is 'TestString' is not declared. It may be inaccessible due to its protection level. (BC30451)

1

There are 1 answers

0
Mark Hurd On BEST ANSWER

Just like normal VB.NET, as well as adding a reference, you have to Imports the relevant namespace, or specify it fully. (You've edited the question to now include this.)

After inserting your code into a new Console project in VS2008 (because that's what I had open) and adjusting for my assembly names, I saw the same as you.

I fixed it by adding Public to the default Module Module1.