[Mono-devel-list] Bug with static field initializers

A Rafael D Teixeira rafaelteixeirabr at hotmail.com
Thu Sep 11 12:05:14 EDT 2003


It's not really a bug, because field initializers, static or not, are just 
code that is executed IN THE ORDER they appear in the source, just before 
the corresponding constructor is executed.

I believe that the CLI speciification mandates this behaviour.

In truth it is a best practice to place all the initialization code only 
inside the appropriate constructor, so that you have better control of the 
process, and can comprehend at a glance how the class is initialized.

Best regards,


Rafael Teixeira
Brazilian Polymath
Mono Hacker since 16 Jul 2001

>From: Chris Seaton <chris at chrisseaton.com>
>To: mono-devel-list at lists.ximian.com
>Subject: [Mono-devel-list] Bug with static field initializers
>Date: Thu, 11 Sep 2003 16:23:25 +0100
>
>Look at the code below. From an abstract overview you would expect it to
>print 14, but the output is 0 (it's clear why, x is initialized before
>y, so when Foo is constructed for x, y is still 0). Is this actually a
>bug, or an excepted restriction?
>
>class Foo
>{
>	public int z;
>
>	public Foo()
>	{
>		z = Bar.y;
>	}
>}
>
>class Bar
>{
>	public static Foo x = new Foo();
>	public static int y = 14;
>
>	public static void Main()
>	{
>		System.Console.WriteLine(x.z);
>	}
>}

_________________________________________________________________
MSN Messenger: instale grátis e converse com seus amigos. 
http://messenger.msn.com.br




More information about the Mono-devel-list mailing list