Shaul Behr
Shaul Behr

Reputation: 38023

When do static declarations get run?

Here's a piece of my code:

public class MyClass {
  public object Value { get; set; }

  public MyClass(object value) {
    this.Value = value;
  }
}

public class AnotherClass {
  private static MyClass _MyObj = new MyClass(new object());

  public static void Main(string[] args) {
    var x = _MyObj; // no problem
    var y = x.Value; // no problem
    var z = y.ToString(); // Null ref exception
  }
}

I don't understand how this can be. _MyObj is not null, which means that the inline assignment did work, yet _MyObj.Value comes out null, meaning that the constructor code wasn't invoked! There's some dark magic at work here, and I'd greatly appreciate an explanation.

Thanks!

EDIT - sorry about the no repro. My actual code is (obviously) more complex than this, so I tried to dumb it down, and obviously in the process I must have removed some other obstruction to the code's proper function. But Kobi's answer is really what I was trying to get out of this question, anyway - so answer credit to him. :)

Upvotes: 0

Views: 111

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273284

Status: No repro.

The code sample as provided does not compile, public object Value { get; } is not a valid auto-property.

After fixing it with a private set; it compiles and runs w/o error.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Put a setter and it will work as expected:

public object Value { get; set; }

Upvotes: 1

Kobi
Kobi

Reputation: 138037

The proper way to initialize static members is by using a static constructor:

static AnotherClass(){
  _MyObj = new MyClass(new object());
}

Upvotes: 2

Related Questions