Terces Eman Terces Eman - 1 year ago 95
MySQL Question

The type initializer for * threw an exception

My problem is that i keep getting an error like this:

The type initializer for 'myproject.GV' threw an exception."

GV there is my class. The code looks fine, no errors when running but after I call on the conn with MySqlConnection the problem will appear.
Example code I try to call conn is this : GV.conn.Open();

Before I put following code to my program it worked fine. Now it keep throwing errors:

public static class GV
public static MySqlConnection conn = new MySqlConnection(
public static MySqlCommand com = null;
public static MySqlDataReader dr = GV.com.ExecuteReader();
public static frmLearnerPanel flp = new frmLearnerPanel();
public static frmLogIn frmLogin = new frmLogIn();

Answer Source

Immediate error that causes this behavior - NullReferenceException in static field inizialization on MySqlDataReader dr = GV.com.ExecuteReader(); (com is null at the time fields are initialized). When there is any exception during static properties initialization whole class marked as failed initialization and any future access to it will throw exception you observe. More info can be found in MSDN article TypeInitializationException.


  • if you really need this data in static fields - wrap code in static method which handle exceptions and never throws. Note that caching reader in static variable is very non-practical as you can only read data from it once.

    public static MySqlDataReader dr = StaticInitializerThatDoesNotThrow();
  • better solution - refactor code to call SQL as necessary and properly dispose connection object. I.e. see for proper call - Retrieve data from a SQL Server database in C#.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download