Re: [Vala] How to initialize static field
- From: "Jan Hudec" <bulb ucw cz>
- To: "Pavel Stupnikov" <dp dpointer org>
- Cc: vala-list gnome org
- Subject: Re: [Vala] How to initialize static field
- Date: Fri, 13 Nov 2009 07:38:19 +0100 (CET)
Hello,
On Fri, November 13, 2009 00:58, Pavel Stupnikov wrote:
I want to create some static fields. Int field works ok, but HashMap
remains null even after initialization... What i did wrong?
You didn't run the initialization. The static constructor only runs when
the corresponding metaobject is requested for the first time. It is only
requested when you create instance, call "class" methods, access "class"
members or use typeof on the type. It is however NOT requested when you
use "static" methods and members.
using Gee;
public static class Foo: Object {
public static HashMap<string, int> bar = new HashMap<string, int>();
This is only executed when you obtain the class object.
If the member was a class one rather than static one, i.e.
public class HashMap<string, int> bar = new HashMap<string, int>();
the initialization would be enforced when accessing it (at the cost of the
access being slightly slower).
public static int a = 5;
However since this is a value type, it can -- and is -- initialized
statically. That means the value is simply stored in the binary and
no code needs to be executed to initialize it.
}
void main () {
To enforce initialization of static members of Foo, you can try putting
typeof(Foo);
here.
stdout.printf("a = %d\n",Foo.a);
stdout.printf("bar: %s\n",(Foo.bar==null?"null":"ok"));
}
prints
a = 5
bar: null
P.S. Same code on mono works fine:
Mono is different thing with completely different runtime semantics.
In this case the difference is, that in CLR access to static members
does require the corresponding metaobject.
Regards,
Jan
--
- Jan Hudec <bulb ucw cz>
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]