Skip to main content

How to Resolve Error "CS0821: Implicitly-typed local variables cannot be fixed" in C#

The Compiler Error CS0821 is a syntax restriction regarding Unsafe Code and Type Inference. The message reads: "Implicitly-typed local variables cannot be fixed".

In C#, the fixed statement is used to pin a managed variable (like an array or string) in memory so that the Garbage Collector does not move it while you access it via a pointer. The var keyword (Implicit Typing) is not allowed inside a fixed statement declaration. When working with pointers, the language design enforces strict type declarations (e.g., int*, char*) to ensure the developer is fully aware of the memory operations being performed.

This guide explains why inference is disabled in unsafe contexts and how to declare fixed pointers correctly.

Understanding the Restriction

The fixed statement declares a pointer variable.

  • Syntax: fixed (PointerType* variableName = expression) ...
  • Context: Unsafe code.

If you write fixed (var p = myArray), you are asking the compiler to infer the type of p. While the compiler technically knows that pinning an int[] results in an int*, the C# specification forbids var here. Unsafe code is dangerous by definition; requiring explicit pointer syntax (int*) acts as a safety check to ensure you know exactly what data type you are pointing to.

Scenario: Using var in a fixed Statement

This error occurs when you try to use var for brevity inside the fixed parentheses, treating it like a standard using or foreach statement.

Example of error

public class UnsafeTest
{
public unsafe void ProcessData()
{
int[] numbers = { 10, 20, 30 };

// ⛔️ Error CS0821: Implicitly-typed local variables cannot be fixed.
// You cannot use 'var' here, even though it's obvious 'p' will be a pointer.
fixed (var p = numbers)
{
System.Console.WriteLine(*p);
}
}
}

Solution: Use Explicit Pointer Syntax

You must explicitly declare the pointer type matching the data you are pinning.

  • If pinning int[], use int*.
  • If pinning string, use char*.
  • If pinning byte[], use byte*.
public class UnsafeTest
{
public unsafe void ProcessData()
{
int[] numbers = { 10, 20, 30 };

// ✅ Correct: Explicitly defined as an integer pointer.
fixed (int* p = numbers)
{
System.Console.WriteLine(*p);
}
}
}

Output:

10

Conclusion

CS0821 ensures clarity in unsafe code.

  1. Identify the Block: Look at your fixed (...) statement.
  2. Check the Type: Did you write var p = ...?
  3. The Fix: Replace var with the specific pointer type (e.g., int*, double*, char*).