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

前端 未结 9 1790
执笔经年
执笔经年 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

    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.

提交回复
热议问题