static field initialization

S

Stephen Lamb

Does anyone know if the standard has anything to say about how static fields
that use other static fields in initialization behave? Pointers into the
standard would be most appreciated. Thanks.

public struct SomeStruct
{
public SomeStruct(int i)
{
I = i;
}

public int I;
}

public struct S1
{
public static SomeStruct S = new SomeStruct(1);
}

public struct S2
{
public static SomeStruct S = new SomeStruct(S1.I);
}

(p.s. Sorry if this doesn't compile, I don't have a compiler from my posting
location.)


Is S2.S.I guaranteed to be 1, 0, or undefined? Does the order in which the
structs are declared change the outcome? If SomeStruct is a class, does
that affect the outcome? If S1.S and S2.S are readonly, does that affect
the outcome? If S1 and S2 are in different namespace, assemblies, etc.?


I've seen instances where S2.S.I == 0 in MSVC 7.1 .NET 1.1 under the
debugger (and the debugger is not displaying 0 when the actual value is 1,
the value really is 0).

Thanks,
Steve
 
J

Jon Skeet [C# MVP]

Stephen Lamb said:
Does anyone know if the standard has anything to say about how static fields
that use other static fields in initialization behave? Pointers into the
standard would be most appreciated. Thanks.

Have a look at section 9.5 of the CLI spec partition 1.
public struct SomeStruct
{
public SomeStruct(int i)
{
I = i;
}

public int I;
}

public struct S1
{
public static SomeStruct S = new SomeStruct(1);
}

public struct S2
{
public static SomeStruct S = new SomeStruct(S1.I);
}

(p.s. Sorry if this doesn't compile, I don't have a compiler from my posting
location.)

Is S2.S.I guaranteed to be 1, 0, or undefined?

1, as you've written it there. It would be 0 if S1 referred to S2
before its declaration of S1 and S1 were referenced before S2 though.
Does the order in which the structs are declared change the outcome?
No.

If SomeStruct is a class, does that affect the outcome?
No.

If S1.S and S2.S are readonly, does that affect
the outcome? If S1 and S2 are in different namespace, assemblies, etc.?
No.

I've seen instances where S2.S.I == 0 in MSVC 7.1 .NET 1.1 under the
debugger (and the debugger is not displaying 0 when the actual value is 1,
the value really is 0).

I wonder whether the debugger is changing things about static
initialization - I wouldn't be surprised.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top