> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C# Unsafe Context

An unsafe context in C# is an explicit code boundary that bypasses the Common Language Runtime's (CLR) memory safety verifications, permitting the direct manipulation of memory using raw pointers. Within this context, the developer assumes full responsibility for memory management, bounds checking, and type safety—operations normally enforced by the runtime and the Garbage Collector (GC).

## Enabling Unsafe Code

Because unsafe code introduces potential memory corruption and security risks, the C# compiler rejects it by default. To compile unsafe code, the project must explicitly opt-in by adding the `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` property to the `.csproj` file, or by passing the `-unsafe` flag to the compiler.

## Declaration Syntax

The `unsafe` modifier establishes the context. It can be applied at various scopes, including entire types, members, or isolated statement blocks.

```csharp theme={"dark"}
// 1. Unsafe Type Scope
public unsafe struct Node
{
    public int Value;
    public Node* Next; // Pointer declaration allowed
}

public class MemoryManager
{
    // 2. Unsafe Method Scope
    public unsafe void ManipulateMemory()
    {
        int x = 10;
        int* ptr = &x; 
    }

    public void SafeMethod()
    {
        // 3. Unsafe Block Scope
        unsafe
        {
            int y = 20;
            int* ptrY = &y;
            *ptrY = 30; // Dereferencing
        }
    }
}
```

## Pointer Mechanics and Restrictions

Inside an unsafe context, C# exposes C-style pointer operators:

* `*` : Pointer declaration and dereferencing.
* `&` : Address-of operator (returns the memory address of a variable).
* `->` : Member access through a pointer.
* `[]` : Pointer element access (pointer arithmetic).

**Unmanaged Types Restriction:** Pointers can only point to *unmanaged types*. An unmanaged type is any type that is not a reference type and does not contain reference type fields at any level of nesting. This includes primitives (`int`, `byte`, `float`, etc.), `enum` types, and `struct` types composed exclusively of unmanaged types. You cannot create a pointer to a `string` or a `class`.

## Memory Pinning with the `fixed` Statement

The CLR's Garbage Collector routinely compacts the managed heap, physically relocating objects in memory. If a raw pointer holds the address of a managed object during a GC cycle, the pointer will become invalid (a dangling pointer) when the object moves.

To safely point to managed data (like an array), the `fixed` statement is required. It "pins" the object, instructing the GC not to relocate it for the duration of the `fixed` block.

```csharp theme={"dark"}
public unsafe void ProcessArray(int[] managedArray)
{
    // Pin the managed array in memory
    fixed (int* ptr = &managedArray[0])
    {
        // The GC will not move managedArray while executing this block
        int* current = ptr;
        for (int i = 0; i < managedArray.Length; i++)
        {
            *current = 0; // Mutate memory directly
            current++;    // Pointer arithmetic
        }
    } // The array is unpinned here
}
```

## Stack Allocation

The `unsafe` context allows the use of the `stackalloc` keyword to allocate a block of memory directly on the thread's execution stack rather than the managed heap. Memory allocated via `stackalloc` is not subject to garbage collection and is automatically discarded when the method returns.

```csharp theme={"dark"}
public unsafe void AllocateOnStack()
{
    // Allocates a contiguous block of 10 integers on the stack
    int* stackArray = stackalloc int[10];

    for (int i = 0; i < 10; i++)
    {
        stackArray[i] = i * 2; // Accessed via pointer indexing
    }
}
```

*(Note: In modern C#, `stackalloc` can be used in safe contexts if assigned to a `Span<T>`, but assigning it to a raw pointer strictly requires an unsafe context).*

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C# Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
