Why does null exist in .NET?

前端 未结 11 1547
醉酒成梦
醉酒成梦 2020-12-24 06:04

Why can values be null in .NET? Is this superior to having a guarantee where everything would have a value and nothing call be null?

Anyone knows what each of these

11条回答
  •  轮回少年
    2020-12-24 06:26

    I speculate that their exists null in .NET because it (C#) followed in the C++/Java foot-steps (and has only started to branch-out in more recent versions) and VB/J++ (which became VB.NET/J#) already had the notion of "nothing" values -- that is, .NET has null because of what was and not because of what it could have been.

    In some languages there is no notion of null -- null can be completely replaced with a type like Maybe -- there is Something (the object) or Nothing (but this is not null! There is no way to get the "Nothing" out of an Maybe!)

    In Scala with Option:

    val opt = Some("foo") // or perhaps, None
    opt match {
       case Some(x) => x.toString() // x not null here, but only by code-contract, e.g. Some(null) would allow it.
       case _ => "nothing :(" // opt contained "Nothing"
    }
    

    This is done by language design in Haskell (null not possible ... at all!) and by library support and careful usage such as in Scala, as shown above. (Scala supports null -- arguably for Java/C# interop -- but it is possible to write Scala code without using this fact unless null is allowed to "leak" about).

    Edit: See Scala: Option Pattern, Scala: Option Cheat Cheet and SO: Use Maybe Type in Haskell. Most of the time talking about Maybe in Haskell brings up the topic of Monads. I won't claim to understand them, but here is a link along with usage of Maybe.

    Happy coding.

提交回复
热议问题