Jaggu
Jaggu

Reputation: 6438

Why would this line throw exception for type initializer failed?

I had a class:

public class Constant
{

    public static string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}

which would throw exception on LIVE: Type initialize failed for Constant ctor

If I change the class to:

public class Constant
{
    public static string ConnString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        }
    }
}

it works. I wasted 2 hours behind this but I still don't know why would this happen. Any ideas?

Note: The 1st class used to work on DEV environment but not on LIVE. The 2nd class works on DEV and also on Production.

I am using VS2010 on production and Asp.Net 4.0 Website project.

I am totally amazed by this inconsistency to say the least!

Edit: This class was in App_Code folder.

Upvotes: 1

Views: 1252

Answers (3)

Marco
Marco

Reputation: 57593

I think the main difference is:

  • The first one is computed when Constant class is initialized
  • The second is evaluated first time ConnString property is accessed (so probably initialization phase is complete)

Upvotes: 2

Benemon
Benemon

Reputation: 73

It may well be that for whatever reason, the ConfigurationManager wasn't initialised when Constant was initialised in the first example. However, Class 2 will go and fetch the property in ConfigurationManager when it's actually needed, rather than when your Constant class is initialised.

Upvotes: 0

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7212

Apparently this line

ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString

will throw an exception on LIVE.

In the first case however this happens in your class constructor so the type initialization fails.

In the second case the exception is delayed until you use the property.

Upvotes: 1

Related Questions