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

前端 未结 9 1834
执笔经年
执笔经年 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 09:36

    In short, .NET wants you to state your intent.

    Sure, the compiler could infer the need for the "unsafe" flag. But the designers want it to be a deliberate decision.

    To me, it's akin to a number of syntactic requirements in C#:

    • no switch case without break
    • no access-level "sections" (such as the "public:" marker in C++)
    • no class fields using "var"

    The pattern is that you shouldn't move or change one thing and inadvertently affect another. Within reason, they want to keep you from "shooting yourself in the foot."

    Lots of great, informative answers here — maybe this goes more to your question.

提交回复
热议问题