0

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. :)

Community
  • 1
  • 1
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387

3 Answers3

2

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

static AnotherClass(){
  _MyObj = new MyClass(new object());
}
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 1
    That's a style issue, your code is exactly the same as `private static MyClass _MyObj = new MyClass(new object());` – H H Dec 22 '09 at 20:23
  • @Henk - I realize that, but it can still help in a more complex scenario, as Shaul said. – Kobi Dec 22 '09 at 21:10
2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
1

Put a setter and it will work as expected:

public object Value { get; set; }
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928