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

1
  • What is the problem - you have a static contstructor that throws an exception. That exception will be a TypeInitializationException as its in the constructor. What is the question? Commented Jun 22, 2010 at 9:29

2 Answers 2

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.