static class instances not allowed?

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 11 09:09:37 PDT 2013


On Tue, 11 Jun 2013 10:04:21 -0400, Eric <eric at makechip.com> wrote:

>
> The following code does not compile:
>
> class Foo { int x; }
> class Bar { static Foo f = new Foo(); }  // compiler error
> static Foo g = new Foo(); // compiler error

These can be solved with a static ctor.  Essentially, any static  
initializers must be evaluatable at compile-time.  I know that in the most  
recent compiler classes have entered this realm, but I don't know the  
conditions on when they can be used.

The accepted way:

class Bar {
   static Foo f;
   static this() { f = new Foo(); }
}

static Foo g;

static this()
{
    g = new Foo();
}

-Steve


More information about the Digitalmars-d-learn mailing list