Andrew
Andrew

Reputation: 1621

Is a static collection guaranteed to be initialized/populated before another class uses it?

Suppose I have these 2 classes:

public class A<T> where T : IEntityWithID, new()
{
    private static EntityInfo entityInfo = B.GetEntityInfo(typeof(T));

    private static IEnumerable TestCases
    {
        // Do work with entityInfo...
    }
}

private static class B
{
    private static IList<EntityInfo> entityInfoList = B.GetEntityList();

    public static EntityInfo GetEntityInfo(Type type)
    {
       return entityInfoList.Single(e => e.Types.Contains(type));
    }

    private static IList<EntityInfo> GetEntityList()
    {
       // Builds a list of EntityInfo's...
    }
}

Is the entityInfoList in class B guaranteed to be initialized and populated before B.GetEntityInfo() is called in class A?

Upvotes: 2

Views: 78

Answers (2)

itsme86
itsme86

Reputation: 19526

Yes, it is guaranteed. Here's a snippet from MSDN:

The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.

EDIT: As pointed out, you could end up in a situation where 2 static classes depend on each other for initialization which could get you in trouble, but as long as that's not the case, you're fine.

Upvotes: 5

Servy
Servy

Reputation: 203819

No, if you have circular dependencies it's possible to run code from a class before that class's static initialization has finished.

Here's a simple example of a static field initialized to 5, and yet an external class observes that field being null:

public class A
{
    public static void Foo()
    {
        Console.WriteLine(B.bar == null);
    }
}

public class B
{
    public static readonly object bar = Foo();

    public static object Foo()
    {
        A.Foo();
        return 5;
    }
}

private static void Main(string[] args)
{
    var bar = B.bar;
}

This will print true.

Upvotes: 4

Related Questions