C# System.TypeInitializationException When Generic Types used

399 Views Asked by At

I am getting a System.TypeInitializationException in C# when i try to call the following:

List<BuyShopItem> buyShopItemList = new List<BuyShopItem>(0);

BuyShopItem is in an external assembly and contains the following:

namespace GameProtocol
{
    public struct BuyShopItem
    {
        public int ShopItemID;
        public int Amount;
        public int GoldPrice;
        public int SilverPrice;
        public int CharacterPointPrice;
        public int ResearchPointPrice;
    }
}

It's probably because of the external assembly, right?

Unfortunately, i cannot change it as i need to pass the BuyShopItem back again to another external Assembly.

Some information about the assembly: It's from a Unity game, .NET 3.5 (according to DotPeek: msil, .Net Framework v3.5)

I'm having the issue in SharpDevelop as well as Visual Studio 2017, so it probably not IDE-related. Result of peverify:

Microsoft (R) .NET Framework PE Verifier. Version  4.0.30319.0
Copyright (c) Microsoft Corporation. Alle Rechte vorbehalten.

[MD]: Error: Field has a duplicate, token=0x040059d7. [Token:0x040059CF]
[MD]: Error: Field has a duplicate, token=0x040059cf. [Token:0x040059D7]
[MD]: Error: Field has a duplicate, token=0x0400a48b. [Token:0x0400A478]
[MD]: Error: Field has a duplicate, token=0x0400a478. [Token:0x0400A48B]
4 Fehler wird/werden überprüft Assembly-CSharp.dll

If you have any Hints of what it could be, please tell me. I will try it out as soon as i can.

Here is a screenshot of the Exception in Visual Studio 2017: https://i.stack.imgur.com/JEySP.png

Update: I just tried the following: Console.WriteLine(typeof(BuyShopItem));, same error occured. Why isn't it possible to get the type?

1

There are 1 best solutions below

1
Peter Aylett On

It is OK to create a zero-length list of structs.

It is also OK to create a list of some type that is defined in a different assembly - but check to make sure that the necessary DLL can be located at runtime.

Instances of structs are generally fairly safe to construct - but check to see if there is a custom constructor that is throwing an exception.

Also carefully check to see if the BuyShowItem struct specifies any static fields that call into other code, which in turn may be failing. This is often the root cause of TypeInitializationException.

See: https://msdn.microsoft.com/en-us/library/system.typeinitializationexception(v=vs.110).aspx