When to use pointers in C#/.NET?

后端 未结 5 674
自闭症患者
自闭症患者 2020-12-02 07:16

I know C# gives the programmer the ability to access, use pointers in an unsafe context. But When is this needed?

At what circumstances, using pointers becomes inevi

5条回答
  •  醉话见心
    2020-12-02 07:41

    The most common reasons to use pointers explicitly in C#:

    • doing low-level work (like string manipulation) that is very performance sensitive,
    • interfacing with unmanaged APIs.

    The reason why the syntax associated with pointers was removed from C# (according to my knowledge and viewpoint — Jon Skeet would answer better B-)) was it turned out to be superfluous in most situations.

    From the language design perspective, once you manage memory by a garbage collector you have to introduce severe constraints on what is and what is not possible to do with pointers. For example, using a pointer to point into the middle of an object can cause severe problems to the GC. Hence, once the restrictions are in place, you can just omit the extra syntax and end up with “automatic” references.

    Also, the ultra-benevolent approach found in C/C++ is a common source of errors. For most situations, where micro-performance doesn't matter at all, it is better to offer tighter rules and constrain the developer in favor of less bugs that would be very hard to discover. Thus for common business applications the so-called “managed” environments like .NET and Java are better suited than languages that presume to work against the bare-metal machine.

提交回复
热议问题