Question

I'm writing a .NET 3.5 application (WinForms) which uses classes from an external DLL and I keep receiving a System.TypeLoadException every time the application tries to start.
Here is the exception VS displays:

System.TypeLoadException was unhandled
  Message=Could not load type 'PolyMorph.Common.Settings' from assembly 'PolyMorph, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
  Source=PolyMorph
  TypeName=PolyMorph.Common.Settings
  StackTrace:
       at PolyMorphApp.App.Initialize()
       at PolyMorphApp.App.Main()
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Here is the code that I'm running:

Friend NotInheritable Class App

    <STAThread()> Shared Sub Main()
        'set the exception handlers'
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
        AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler
        'initialize the application'
        App.Initialize()

        'and then run the application'
        Dim mainForm As New PolymorphHost
        Application.Run(mainForm)
    End Sub

    Shared Function Initialize() As FunctionResult
        If App.InitializeDataDirectory() = False Then
            Return New FunctionResult(False, "the application's data directory")
        End If


        _settings = New PolyMorph.Common.Settings(AppDataDirectory & "\Settings.dat")
        ......code continues to load settings from the _settings variable
    End Function
End Class



What surprises me is that the VS2010 Debugger stops on the line App.Initialize() without even stepping into the Initialize function.

If, however, I comment out all references to the external DLL in the Initialize function, the application initializes properly.


After reading around, I realized that a number of people reporting this error were using different builds on their projects (as in x64 DLL being referenced from an x86 application). I therefore changed the build configuration so the DLL and the application were both x86 but I still have the TypeLoadException.

Is there anything I'm missing?

Was it helpful?

Solution 2

It appears one Nutzy also had a similar problem and he solved it by copying all the classes, forms and controls to a new project. I did likewise and the problem was solved.

Thanks, Jim Mischel and Paul Alexander for your assistance. I voted you up for your efforts to help me solve the problem.

OTHER TIPS

You should look at the InnerException and LoadException properties to get a better detail on why the dependent assembly isn't loading properly.

The reason it's throwing the exception before Initialize is due to the way the method is JIT compiled. When a method is executed the first time, the CLR will validate and resolve all of the MSIL instructions in that method before compiling it into it's runtime equivalent. Since the PolyMorph.Common.Settings type is used by the Initialize method, the CLR tries to resolve it when compiling. Since the load fails, Initialize is never executed.

to capture the exception in your own code, just move the entire Initialize code to another method, then invoke that method in a try...catch block from Initialize.

Try
    InitializeInternal()
Catch ex As TypeLoadException
    System.Diagnostics.Debugger.WriteLine(ex.ToString())
End Try

The most likely cause is that it's throwing an exception when trying to load one of the settings. You might try setting a breakpoint at the first statement in the Initialize method. That might give you the opportunity to single-step and see where the error is.

Or you could use Debug statements (see System.Diagnostics) after each value is loaded, to determine where it's failing.

I had the same problem, and I'm convinced it is a bug in VisualStudio or the JIT compiler. I know it has nothing to do with DLLs or x64 vs x86, since I had no custom references in my test project. I tracked down the offending line to a member variable of a struct. There was nothing interesting about that particular member variable (it was a simple class:)

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Foo
    {
        int x;
    }

and it was a member as follows. It works if the #if was true. If I change it to #false, it compiles without error, but then at run time, when I access anything at all in the entire class, it gives me the TypeLoadException

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct uartparam_t
    { //size 112
        public UInt16 portnum; //0
        public Byte conntype;
        public Byte baud;
        public Byte databits;
        public Byte stopbits;
        public Byte parity;
        public Byte flowctrl;
#if true
        public int remoteip;
#else
        public Foo remoteip; //8 -- for some reason this is making the program crash! ?!?!?
#endif

     ....

which was part of

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct config {
 ...
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAXUARTPORT)]
        public uartparam_t[] uartparam; //(size 1792)
 ...
    }

It doesn't make any sense. I tried a full rebuild of the application, as well as creating a new project in a new solution, and none of that helped. The only way to get it to work was to change the struct to an int, and deal with the type conversion from int to Foo outside of the struct.

I often get this error when I am adding code to our product. The issue we run into is that the latest version of the product is installed in the GAC and I am trying to test a new feature on my developer machine. The app that I run depends on a new feature that I build locally, but the app loads the assembly from the GAC wich does not contain the new feature. When I uninstall the product, the exception goes away.

My problem was the parent assembly and the DLL had the same assembly name.

e.g. Application.exe and Application.dll

I changed each to a separate name in the project properties (e.g. Application.exe and Library.dll) and it fixed the problem. I guess the selected answer ("transferring to a new solution") they're re-naming the projects as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top