Search code examples
c#typeinitializationexception

Type Initialization Exception when using a static field


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TypeIntailization_Exception
{

    class TypeInit
    {
        // Static constructor
        static TypeInit()
        {

        }
        static readonly TypeInit instance = new TypeInit();
        public  static TypeInit Instance
        {
            get { return instance; }
        }
        TypeInit() { }
    }
    class TestTypeInit
    {
        static public void Main()
        {

            TypeInit t = TypeInit.Instance;

        }
    }

}

when running this i get Type InTialization Exception how can i avoid this...


Solution

  • The TypeInitializationException is thrown when an exception is thrown by the class initializer (in your example static TypeInit().

    You can see the real exception by examining the InnerException property of the TypeInitializationException:

    static public void Main()
    {
        try
        {
            TypeInit t = TypeInit.Instance;
        }
        catch (TypeInitializationException tiex)
        {
            var ex = tiex.InnerException;
    
            Console.WriteLine("Exception from type init: '{0}'", ex.Message);
        }
    }