-
Notifications
You must be signed in to change notification settings - Fork 1
Pointers
Mario Gutierrez edited this page Jan 7, 2017
·
1 revision
Though rarely used in C# development, you can actually use pointers.
To use you need to:
- Define the
/unsafe
flag on compilation:csc /unsafe *.cs
- Enable the 'Allow unsafe code' option in Visual Studio.
- Use the unsafe keyword for blocks and methods.
class Program
{
static void Main(string[] args)
{
unsafe
{
int myInt = 5;
Square(&myInt);
}
}
unsafe static void Square(int *n)
{
return *n *= *n;
}
}
unsafe struct Node { /* ... */ }
struct Node
{
public int Value;
public unsafe Node* next; // Unsafe field.
}
Unlike in C and C++, the * operator must be next to the type for pointer declaration, e.g.,
public unsafe Node* left, right; // C#
instead of,
public Node *left, *right; // C, C++
char* p = stackalloc char[256]; // Declare memory on the stack.
To prevent a ReferenceType
from being swept or moved by the GC while
you are using its address, use the fixed
keyword.
fixed (MyRefType* p = &refVar)
{
Console.Write(p->ToString());
}
Console.Write(sizeof(int));
// Must be in an 'unsafe' block for custom types.
unsafe { Console.Write(sizeof(Point)); }
- Abstract Classes
- Access Modifiers
- Anonymous Methods
- Anonymous Types
- Arrays
- Attributes
- Console I/O
- Constructors
- Const Fields
- Delegates
- Enums
- Exceptions
- Extension Methods
- File IO
- Generics
- Interfaces
- Iterators
- LINQ
- Main
- Null Operators
- Parameters
- Polymorphism
- Virtual Functions
- Reflection
- Serialization
- Strings
- Value Types
- "Base" Keyword
- "Is" and "As"
- "Sealed" Keyword
- nameof expression