Why does null exist in .NET?

前端 未结 11 1550
醉酒成梦
醉酒成梦 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:36

    null is just the name of the default value for a reference type. If null was not allowed, then the concept of "doesn't have a value" wouldn't go away, you would just represent it in a different way. In addition to having a special name, this default value also has special semantics in the event that it is misused - i.e. if you treat it like there is a value, when in fact there is not.

    If there were no null:

    1. You would need to define sentinel default values for your types to use when "there is no value". As a trivial example, consider the last node of a forward singly-linked list.
    2. You would need to define semantics for operations performed on all of these sentinel values.
    3. The runtime would have additional overhead for handling the sentinel values. In modern virtual machines such as the ones used by .NET and Java, there is no overhead for null-checking prior to most function calls and dereferences because the CPU provides special ways to handle this case, and the CPU is optimized for cases where the references are non-null (e.g. branch prediction).

    In summary:

    • The name would change, but the concept would not.
    • The burden of defining and communicating the default value and semantics for cases where you have "no value" is placed on developers and developer documentation.
    • Code executing on modern virtual machines would face code bloat and substantial performance degradation for many algorithms.

    The problems with null described by Tony Hoare are typically due to the fact that prior to modern virtual machines, runtime systems did not have nearly as clean handling of misused null values like you have today. Misusing pointers/references does remain a problem, but tracking down the problem when working with .NET or Java tends to be much easier than it used to be in e.g. C.

提交回复
热议问题