Why there\'s a NullReferenceException when trying to set value of X in the code below? It works fine when I use new
keyword when initializing B
, bu
Initialization syntax can be tricky. In your code, you're trying to set the value of a.B.X
without first setting the value of B
. Your code translates to:
var a = new A();
a.B.X = 1;
... which would produce the same exception you're getting now. That's because a.B
is initialized to null
unless you explicitly create an instance for it.
As you noted, this will work:
var a=new A{
B= new _B {
X=1
}
};
You could also make sure that A
's constructor initializes a B
.
public class A
{
public _B B = new A._B();
public class _B
{
public int X;
}
}
why it compiles fine without new and then fails during runtime?
It would require too much work for the compiler to dig into the code for your A
class and realize that B
will definitely be null at this point in time: as I pointed out you could change the implementation of A
's constructor to make sure that's not the case. This is one reason that null reference exceptions are the most common type of exception out there.
The best strategy to avoid this is to initialize all of your fields to non-null values in the constructor. If you won't know what value to give them until your constructor is invoked, then make your constructor take those values as parameters. If you expect one of your fields may not always have a value, you can use an optional type like my Maybe<> struct to force programmers to deal with that fact at compile-time.