Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeInitializationException exception on creating an object

I have an assembly (class library project in .Net 3.5) that has some references like System.Configuration and System.Web. I use it on a web application and it works fine.

Now, I need to make a reference to a Windows Forms project and I can't understand what is happening. When I try to create an instance of my class it does not work; an exception of type TypeInitializationException is thrown.

I try to create other instances of my assembly and those work, except this specific class.

Does anybody know what is happening?

like image 537
Felipe Oriani Avatar asked Aug 10 '11 20:08

Felipe Oriani


People also ask

How do I fix the initializer for threw an exception?

Click Debug--> Exceptions and check ON all the Thrown checkboxes. This will cause the debugger to stop on all first chance exceptions and will help you find the error under the Type Initializer error that you're seeing.

What is TypeInitializationException?

Typically, the TypeInitializationException exception reflects a catastrophic condition (the runtime is unable to instantiate a type) that prevents an application from continuing. Most commonly, the TypeInitializationException is thrown in response to some change in the executing environment of the application.

What is type initializer in C#?

Type Initializers are a new language construct that allow for C# (and VB using similar syntax) to shortcut creating of custom constructors or writing additional code to initialize properties.


3 Answers

TypeInitializationException is usually thrown when a static field of the class can't be initialized. For example:

class BadClass
{
    private static MyClass fieldName = new MyClass();
}

Will cause a TypeInitializationException prior to the first usage of BadClass if the constructor for MyClass throws.

You can look at the InnerException property of the TypeInitializationException to drill down into the cause of the failure in more detail. It will usually point you to the underlying exception that caused the type initialization to fail.

like image 113
Timothy Fries Avatar answered Oct 11 '22 01:10

Timothy Fries


TypeInitializationException is thrown when the class initializer fails. There can be a number of reasons to this, but most likely you have some code in your class' static constructor, that throws an exception. You can likely look at the InnerException property to get the real exception.

like image 10
driis Avatar answered Oct 11 '22 03:10

driis


Just to catch another scenario, this error will be thrown when your AppConfig contains a section that is not defined in the configSections node. It's case sensitive, so verify that your custom config sections match what's in the configSections node.

like image 4
Travis Avatar answered Oct 11 '22 03:10

Travis