Pointers
Until now, you've seen no code using C-/C++-style pointers. Only here, in the final paragraphs of the final pages of the book, does this topic arise, even though pointers are central to the C family of languages. In C#, pointers are relegated to unusual and advanced programming; typically, they are used only with P/Invoke.
C# supports the usual C pointer operators, listed in Table 23-1.
Table 23-1. C# pointer operators
Operator | Meaning |
|---|---|
& | The address-of operator returns a pointer to the address of a value |
* | The dereference operator returns the value at the address of a pointer |
-> | The member access operator is used to access the members of a type |
The use of pointers is almost never required, and is nearly always discouraged. When you do use pointers, you must mark your code with the C# unsafe modifier. The code is marked unsafe because you can manipulate memory locations directly with pointers. This is a feat that is otherwise impossible within a C# program. In unsafe code, you can directly access memory, perform conversions between pointers and integral types, take the address of variables, and so forth. In exchange, you give up garbage collection and protection against uninitialized variables, dangling pointers, and accessing memory beyond the bounds of an array. In essence, unsafe code creates an island of C++ code within your otherwise safe C# application, and your code will not work in partial-trust scenarios.
As an example of when this might be useful, read a file to the console ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access