Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use pointers (unsafe code) in C#?

Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?

like image 233
Kredns Avatar asked Feb 24 '09 23:02

Kredns


People also ask

Why are pointers considered unsafe?

Pointers are powerful because they allow you to directly access memory addresses. This same usefulness also makes them very dangerous. If you don't use your pointers correctly you can access garbage data or leave them dangling. Another product of incorrect usage is memory leaks.

What are unsafe pointers?

Pointer is like the void* in C language. Go unsafe pointers mean the types whose underlying types are unsafe. Pointer . The zero values of unsafe pointers are also represented with the predeclared identifier nil . Before Go 1.17, the unsafe standard package has already provided three functions.

Should you use pointers in C#?

The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases: Dealing with existing structures on disk. Advanced COM or Platform Invoke scenarios that involve structures with pointers in them.


1 Answers

From "The Man" himself:

The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases:

  • Dealing with existing structures on disk
  • Advanced COM or Platform Invoke scenarios that involve structures with pointers in them
  • Performance-critical code

The use of unsafe context in other situations is discouraged.

Specifically, an unsafe context should not be used to attempt to write C code in C#.

Caution:

Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet.

Reference

like image 179
rbrayb Avatar answered Sep 28 '22 11:09

rbrayb