C#: Benefit of explicitly stating “unsafe” / compiler option

前端 未结 9 1719
执笔经年
执笔经年 2021-01-12 09:13

I understand pointers and the rare need to use them in C# code. My question is: what is the reasoning behind having to explicitly state \"unsafe\" in a block of code. Additi

相关标签:
9条回答
  • 2021-01-12 10:01

    Actually the CLR makes no requirements at all about an /unsafe switch or keyword. In fact, C++/CLI (the C++ language that runs under the CLR) has no such /unsafe switch, and pointers can be used freely on the CLR.

    So I would rephrase your question as "Why does C# require the use of /unsafe before pointers can be used?" And the answer to that question is as stated in other answers given here: to help the user make a conscious decision to lose the ability to run in anything less than Full Trust mode on the CLR. C++ virtually always requires Full Trust on the CLR, and C# can whenever you call code that requires Full Trust, or whenever you use pointers.

    0 讨论(0)
  • 2021-01-12 10:01

    Think about it from the opposite point of view: because it's not marked unsafe, you can infer that most code is "safe" by default. So what does it mean to be "safe"? For .Net code, this includes (but may not be limited to):

    • The garbage collector can do business as usual.
    • References to a specific type will refer to objects of that type (or null).
    • Code is guaranteed to comply with .Net trust/security requirements.
    • The code is mathematically proven not to directly touch memory outside it's own AppDomain. It may seem trivial, but imagine if you have multiple AppDomains in the same application. The programmer can confidently treat them as logically separate.

    Any time you use pointers you have the chance to break any of those guarantees. Therefore marking code as unsafe gives up those protections.

    0 讨论(0)
  • 2021-01-12 10:03

    Nurturing good habits & security. Whenever you use an unsafe block in an assembly, a NativeCode permission will be demanded from the stack. This could of course be done implicitly, but couldn't we also just remove the private keyword completely? I think it's good to force developers to specifically require unsafe code before they can use it.

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