Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be the reason that I get TypeInitializationException when I call a static method on a class?

Tags:

c#

.net

exception

I have a static method on a public class. Example:

public class MyClass {
 public static bool Test() { return true; }
}

And I call this from a unit test in another class:

MyClass.Test();

When the debugger comes to this it throws: TypeInitializationException:

{"The type initializer for 'Xxxxx.Yyyyy.MyClass' threw an exception."}

Inner Exception says:

{"Value cannot be null.\r\nParameter name: container"}

Any idea why it may be the case?

Note: This is a class in a console application - if it is important.

like image 478
pencilCake Avatar asked Dec 22 '22 02:12

pencilCake


1 Answers

A TypeInitializationException is thrown when an exception occurs during the initialization of the type (as opposed to an instance of the type).

This generally means it is caused by an exception in a static constructor or where static fields are initialized.

One important thing to bear in mind when trying to find the cause is this: Once a type has thrown this exception once - it will always throw it every other time you try and access the type. This means that to get to the bottom of it, you may have to hunt down where it is first thrown, rather than where it is thrown subsequently.

[Edit: in response to your updated question] Can you post a more complete MyClass? It is doing something when the type itself is initialized causing it to throw this.

like image 97
Rob Levine Avatar answered Dec 24 '22 02:12

Rob Levine