[Mono-list] mcs bug, using non-initialized static member variables?

A Rafael D Teixeira rafaelteixeirabr@hotmail.com
Sun, 09 Jun 2002 16:03:13 -0300


>From: Jaime Anguiano Olarra <jaime@geneura.ugr.es>
>Subject: [Mono-list] mcs bug, using non-initialized static member 
>variables?

>	I've read that: you must initialize all static member variables
>(what is logical if you are not initializing then at the time you create
>instances). The fact is that I can compile a class with such a variable
>member using mcs 0.11, f.ex:
>
>  ...
>  private static int counter;
>
>	Can anyone tell me if it's a bug in the mcs or in the documentation I 
>read?.

It´s a logical error, not a sintactic one, see mcs/mcs/driver.cs for lots of 
static uninitialized ArrayLists, for examples. What mcs doesn´t know how to 
do yet is flow analisys (csc does), to alert you when you try to USE any 
field/variable without initializing it first.

You must initialize static fields, before use, but there are at least 4 ways 
you can accomplish it:

1 - doing nothing: the runtime initializes objects to null (for value types 
it not advisable to do that).

.. private static int counter;

2 - with a initializer whithin the declaration:

.. private static int counter = 0;

3 - with a static constructor: it is guaranteed to be called only once, 
before any use of the class.

.. class Something
.. {
..   private static int counter;
..
..   static Something()
..   {
..     counter = 0;
..   }
.. }

4 - inside of a instance constructor: but beware this resets the field 
anytime an instance is created, and is run many times, not just once, even 
if you use another static field as an flag to avoid resetting, you are 
penalizing performance.

.. class Something
.. {
..   private static bool counterInitialized = false;
..   private static int counter;
..
..   Something()
..   {
..     if (!counterInitialized)
..     {
..       counter = 0;
..       counterInitialized = true;
..     }
..   }
.. }


Rafael Teixeira
Brazilian Developer


_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com