C# Pointer Types (Unsafe Context)
Pointer types in C# are used to work with memory addresses directly. However, they can only be used in an unsafe
context. A pointer is declared using an asterisk (*
), and the unsafe
keyword must be used when working with them.
Key Concepts
- Pointers are variables that store the memory address of another variable.
- They can only be used in an
unsafe
block or method. - Pointers are primarily used for advanced memory manipulation.
Example of Using Pointers
Code Example
// Unsafe code block to use pointers
unsafe {
int var = 20;
// Declare a pointer to the variable
int* p = &var; // Pointer stores the memory address of var
// Output the memory address stored in the pointer
Console.WriteLine((int)p);
// Output the value stored at the memory address
Console.WriteLine(*p);
}
Output:
(Memory address of the variable 'var')
20
Code Explanation: The pointer p
stores the memory address of the variable var
. The &
symbol is used to get the address of the variable, and the *
operator dereferences the pointer to access the value stored at that address. Both the memory address and the value are printed to the console.
Output Explanation: The first line prints the memory address of the variable var
. The second line prints the value 20
, which is the value stored at that memory address.