The type initializer for ‘MyClass’ threw an exception

Description

   In this article I am going to explain about what would be the cause for the error The type initializer for ‘MyClass’ threw an exception.

Summary

   I got the error The type initializer for threw an exception while debugging my C# project in Visual Studio. When I google about the error The type initializer for threw an exception I got more suggestion to resolve this error. most of the suggestions are asked me to see what is the Inner Exception message of this error, I got the error message Value cannot be null. Parameter name: string in inner exception. The finally I found the following solution for my issue.

Solution -The type initializer for threw an exception

Finally I found reason for this issue is AppConfig settings of my project. Yes, I have two C# projects, Project1 and Project2.

 Project1 is contains the Static class MyDetails

public static MyDetails
{
  public static int _LogLevel = Int32.Parse(ConfigurationManager.AppSettings["LogLevel"])

  public static GetData()
   {
     ----code----
     ----code----
   }
}

I have following appConfig settings in Project1

<appSettings>
    <add key=”LogLevel” value=”5″/>
</appSettings>

 The function MyDetails.GetData() is being called From Project2 which is the project I am debugging now. Since Project2  is the target project,  the line ConfigurationManager.AppSettings[“LogLevel”] will try to read setting LogLevel from Project2. but LogLevel setting is only available in Project1. so, we need to add appsettings in Project2.

The issue The type initializer for threw an exception has been solved after adding  the folowing appsettings in appConfig of Project2,

<appSettings>
    <add key=”LogLevel” value=”5″/>
</appSettings>

Thanks,
Morgan
Software Developer

Advertisement

4 thoughts on “The type initializer for ‘MyClass’ threw an exception”

    • Hi Alex, what help you want?…I strongly believe you faced this issue 'The type initializer for 'MyClass' threw an exception'……this is my quick response ….please check the App.config file of referenced project

      Reply

Leave a Comment