tags:

views:

68

answers:

3

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

+2  A: 

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

static AnotherClass(){
  _MyObj = new MyClass(new object());
}
Kobi
That's a style issue, your code is exactly the same as `private static MyClass _MyObj = new MyClass(new object());`
Henk Holterman
@Henk - I realize that, but it can still help in a more complex scenario, as Shaul said.
Kobi
+1  A: 

Put a setter and it will work as expected:

public object Value { get; set; }
Darin Dimitrov
+2  A: 

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.

Henk Holterman