C# – System.TypeInitializationException: ‘The type initializer threw an exception.’

cnet

I've a simple class MyClass with a method defined in a DLL, now I refer to this DLL in another code and try to initialise object like this Myclass obj = new MyClass(). I'm not sure why compiler is throwing NullReferenceException. Please assist

DLL:

public class MyClass
{
    public MyClass(){}
    public void method()
    {
         //some code
    }
}

Other code:

void main()
{
    MyClass obj=new MyClass(); //This is where I get NullReferenceException error
}

Best Answer

For posterity, since we found the answer in the comments:

TypeInitializationException is usually caused by an error in static field initialization or static constructor execution.

Indeed we found that the inner exception stack trace pointed to :

SqlConStr = ConfigurationManager.ConnectionStrings["RMDB.Database"].Conn‌​ectionString

This error is caused by the fact that the connection string RMDB.Database was not specified in the app.config for the application. Connection strings (event those used from dlls) must be specified in the app.config of the application using the connection.