开发者

order initializiation static parameter

开发者 https://www.devze.com 2023-02-06 22:19 出处:网络
Is there any specification for the order in which static readonly parameters are initialized? In the following example, can one be sure, the array is always created with a length of 6?

Is there any specification for the order in which static readonly parameters are initialized?

In the following example, can one be sure, the array is always created with a length of 6?

public class Foo {
    private static readonly int MAX_STACKSIZE = 6; 
    private static readonly int[] m_stack = new int[MAX_STACKSIZE]; 
}

Or is there any chance of m_stack being initialized before MAX_STACKSIZE ?

开发者_开发技巧

@Edit: changed const to static readonly


EDIT: This answer was written when the sample code contained "const" instead of "static readonly". It's not valid for the current version of the question - I may write another answer to deal with that at some point, but I don't have time right now.

That won't be valid C# anyway, as you can't set a const int[] to anything other than null.

However, in the more general case, section 10.4 of the C# spec applies:

Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.

It then gives the following example:

class A
{
    public const int X = B.Z + 1;
    public const int Y = 10;
}

class B
{
    public const int Z = A.Y + 1;
}

and says...

the compiler first evaluates A.Y, then evaluates B.Z, and finally evaluates A.X, producing the values 10, 11 and 12 in that order.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号