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

Matt Greenwood matt at thegreenwoods.org
Fri Sep 12 15:44:50 EDT 2003

This is more or less true, but not exact. Each Type may also have a
static initializer (.cctor). If both field initializers and a static
type initializer are given, then the combined static initailizer will
first initialize those fields (in order of declaration) and then the
body of the static type initializer. For example,

public sealed class A {
	static A() {
		x = 5;
	private static int x;
	private static int y = 6;
	private static int z = 10;

Will initialize y and z *before* x.


-----Original Message-----
From: A Rafael D Teixeira [mailto:rafaelteixeirabr at hotmail.com] 
Sent: Thursday, September 11, 2003 12:05 PM
To: chris at chrisseaton.com; mono-devel-list at lists.ximian.com
Subject: Re: [Mono-devel-list] Bug with static field initializers

It's not really a bug, because field initializers, static or not, are
code that is executed IN THE ORDER they appear in the source, just
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
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. 

Mono-devel-list mailing list
Mono-devel-list at lists.ximian.com

More information about the Mono-devel-list mailing list