Unsafe code in C# allows developers to work directly with memory addresses and perform low-level operations. It provides a way to bypass the type safety and memory management features of the Common Language Runtime (CLR).
Unsafe code is a feature in C# that enables direct memory manipulation and pointer arithmetic. It's called "unsafe" because it can potentially lead to memory corruption or security vulnerabilities if not used carefully.
Unsafe code is typically used in scenarios where performance is critical or when interacting with unmanaged code. Common use cases include:
To use unsafe code, you need to mark the relevant code block or method with the unsafe
keyword. Here's a basic example:
unsafe void PointerExample()
{
int x = 10;
int* ptr = &x;
Console.WriteLine(*ptr); // Output: 10
}
In this example, we declare a pointer to an integer and assign it the address of variable x
. We then dereference the pointer to print its value.
When working with arrays or strings in unsafe code, you need to use the fixed
statement to pin the object in memory. This prevents the garbage collector from moving it during pointer operations.
unsafe void FixedExample()
{
int[] numbers = { 1, 2, 3, 4, 5 };
fixed (int* ptr = numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(ptr[i]);
}
}
}
Unsafe code interacts with several other C# concepts:
While unsafe code provides powerful capabilities for low-level operations, it should be used judiciously. Always prioritize safe code practices and only resort to unsafe code when absolutely necessary for performance or interoperability reasons.