What is the CLR implementation behind raising/generating a null reference exception?

前端 未结 3 765
旧时难觅i
旧时难觅i 2021-01-18 21:16

We do come across this particular and one of the most common exception in our coding/development life day or another day. My Question is NOT about W

3条回答
  •  死守一世寂寞
    2021-01-18 22:06

    The MS implementation, IIRC, does this via an access violation. Null is essentially a zero reference, and basically: they deliberately reserve that address space and leave this page unmapped. The memory access violation is raised at the CPU/OS level automatically (i.e. without needing extra code to do a null check), and the CLI then reports this as a null-reference exception.

    Interestingly, because memory is handled in pages, you can actually simulate (if you try hard enough) a null-reference exception on a non-zero but low value, for the same reasons.

    Edit: Eric Lippert discusses this on this related question/answer: https://stackoverflow.com/a/8681563

提交回复
热议问题