NullReferenceException during object initialization [duplicate]

南笙酒味 提交于 2019-12-04 02:19:35

问题


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, but why it compiles fine without new and then fails during runtime?

https://dotnetfiddle.net/YNvPog

public class A
{
    public _B B;
    public class _B
    {
        public int X;
    }
}

public class Program
{
    public static void Main()
    {
        var a=new A{
                B={
                    X=1
                }
            };
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/33265394/nullreferenceexception-during-object-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!