Say I have the following dictionary like so:
public static Dictionary<Type, string> nullableTypeToStringMap = new Dictionary<Type, string>()
{
{typeof(bool?) , "bool?"},
{typeof(byte?) , "byte?"},
{typeof(sbyte?) , "sbyte?"},
{typeof(char?) , "char?"},
{typeof(decimal?) , "decimal?"},
{typeof(double?) , "double?"},
{typeof(float?) , "float?"},
{typeof(int?) , "int?"},
{typeof(uint?) , "uint?"},
{typeof(long?) , "long?"},
{typeof(ulong?) , "ulong?"},
{typeof(short?) , "short?"},
{typeof(ushort?) , "ushort?"}
};
and say I have execute this line:
nullableTypeToStringMap [typeof(int?)];
I get the following exception: The type initializer for 'DatabaseUtils.Utils.TypeMap' threw an exception.
However, if I execute this line:
nullableTypeToStringMap [typeof(int)];
It works fine. Any idea why the nullable type is causing me issues?
My psychic debugging skills tell me that your code is in an earlier static field initializer, so it’s running before you assign
nullableTypeToStringMap.You need to order the static fields so that you don’t use a field before initializing it.