Question

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...

Was it helpful?

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);
    }
}

OTHER TIPS

You are throwing an exception in the constructor of your singleton class, so the moment you are trying to construct it it throws an exception. This gets wrapped in the TypeInitializationException as you see.

Solution: don't throw an exception unless it is warrented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top