Why is “null” present in C# and Java?

前端 未结 25 1808
别那么骄傲
别那么骄傲 2020-11-29 22:09

We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.

Is there a reason why \"null\" has even been included in the l

相关标签:
25条回答
  • 2020-11-29 22:48

    Besides ALL of the reasons already mentioned, NULL is needed when you need a placeholder for a not-yet created object. For example. if you have a circular reference between a pair of objects, then you need null since you cannot instantiate both simultaneously.

    class A {
      B fieldb;
    }
    
    class B {
      A fielda;
    }
    
    A a = new A() // a.fieldb is null
    B b = new B() { fielda = a } // b.fielda isnt
    a.fieldb = b // now it isnt null anymore
    

    Edit: You may be able to pull out a language that works without nulls, but it will definitely not be an object oriented language. For example, prolog doesn't have null values.

    0 讨论(0)
提交回复
热议问题